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 / Operation | Description |
|---|---|
| Box::new(v) | Allocates value v on the heap and returns a Box. |
| *b | Accesses 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 contact us.