Box<T> (Rust)
Box<T> is the simplest smart pointer: it stores a value on the heap instead of the stack, with single ownership. It's used for large values, recursive types, and trait objects.
Rust
Box<T> allocates its contents on the heap and holds a pointer on the stack. When the Box is dropped, the heap value is freed automatically — ownership is single and clear. There is no reference counting and almost no overhead beyond the allocation itself.
The three classic uses are: storing recursive types whose size can't be known at compile time (a linked list or tree node), moving a large value to avoid copying it on the stack, and creating trait objects with Box<dyn Trait> for dynamic dispatch.
Box is the baseline; reach for Rc when you need shared ownership, RefCell for interior mutability, and Arc/Mutex for sharing across threads. Box gives you the heap without any sharing.
Syntax
let boxed: Box<i32> = Box::new(5);
let obj: Box<dyn Trait> = Box::new(value);Examples
Rust
fn main() {
let n = Box::new(42);
println!("{}", *n + 1);
}Output:
43