Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Box<T>

Box<T>

Box<T> is a smart pointer that allocates a value on the heap. Use it to store types whose size is unknown at compile time, to define recursive data structures, or to hold trait objects.

Syntax

// Allocates a value on the heap.
let b = Box::new(value);

// Accessing the inner value (automatically dereferenced)
*b

// Trait object (dynamic dispatch)
let obj: Box<dyn TraitName> = Box::new(value);

// Recursive data structure
enum List {
    Cons(i32, Box<List>),
    Nil,
}

Method List

Method / OperationDescription
Box::new(v)Allocates value v on the heap and returns a Box.
*bAccesses the inner value via the Deref trait.
Box<dyn Trait>Holds a trait object. Dispatched dynamically at runtime.
drop(b)When a Box goes out of scope, both the box and its contents are automatically freed.

Sample Code

// Trait definition
trait Animal {
    fn sound(&self) -> &str;
}

struct Dog;
struct Cat;

impl Animal for Dog {
    fn sound(&self) -> &str { "woof" }
}
impl Animal for Cat {
    fn sound(&self) -> &str { "meow" }
}

// Recursive list structure (without Box, this would fail to compile)
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn main() {
    // Basic usage: allocate a value on the heap.
    let b = Box::new(5);
    println!("{}", *b); // 5 (dereferenced via Deref)

    // Trait objects: different types can be stored in the same Vec.
    let animals: Vec<Box<dyn Animal>> = vec![
        Box::new(Dog),
        Box::new(Cat),
    ];
    for a in &animals {
        println!("{}", a.sound()); // woof / meow
    }

    // Recursive list: Cons(1, Cons(2, Cons(3, Nil)))
    let list = List::Cons(1,
        Box::new(List::Cons(2,
            Box::new(List::Cons(3,
                Box::new(List::Nil))))));

    // b is automatically freed when it goes out of scope.
}

Notes

Because Box<T> places its value on the heap rather than the stack, it can hold types whose size is not known at compile time, such as recursive types. Using Box<dyn Trait> to hold a trait object enables dynamic dispatch, letting you work with different concrete types through a single interface.

Thanks to Rust's Deref trait, Box<T> is automatically dereferenced in most contexts, so you can use it just like a regular reference (deref coercion).

Box does not implement Clone automatically. Even if the inner type implements Clone, you need #[derive(Clone)] or an explicit implementation to clone the Box itself.

If you find any errors or copyright issues, please .