`Box`
Box<T> is an owned heap allocation of a single T. When the box drops, it drops T and frees the memory. It is the simplest smart pointer.
Detailed Explanation
Box::new(session) allocates enough heap for Session, moves the value there, and returns a pointer you own. Dereference with * or call methods through autoderef: b.user_id works as if b were a Session. There is no reference count and no interior mutability. One box, one owner.
Why heap-allocate a single value? Three reasons. Recursive types: struct Node { next: Box<Node> } has a known size because the Box is a pointer; struct Node { next: Node } would be infinite. Trait objects: Box<dyn Error> is an owned erased error. Large values you want to move cheaply: moving a Box<Big> copies a pointer, not the Big.
Box<[T]> is an owned slice with no spare capacity — a Vec you cannot grow. Vec::into_boxed_slice throws away capacity. Box<str> is the same idea for text. These show up when you are done building and want to keep the data without the extra word of capacity.
Box is Send and Sync when T is. It is Unpin in the usual cases; Box<T> is always Unpin even if T is not, because the box can move while the T stays at a stable heap address. That is why Box<dyn Future> is a common type-erased future.
There is no garbage collector. Cycles of Box cannot be expressed because Box is exclusive. Cycles need Rc/Weak or Arc/Weak. Box is not Rc. Cloning a Box<T> requires T: Clone and allocates a second T.
When you reach for Box: recursion, trait objects you own, huge values you move often. When you reach for Rc/Arc: shared ownership. When you reach for Vec: many values, not one.
Code Examples
enum List {
Nil,
Cons(i32, Box<List>),
}
fn main() {
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
let boxed = Box::new(17);
println!("{}", *boxed); // prints: 17
let _ = list;
}Common Gotchas
A recursive type without `Box` (or another pointer) will not compile
The compiler cannot size `struct Node { next: Node }`. Put the recursive field behind `Box`.
`Box<T>` is not shared
Two owners need `Rc` or `Arc`. Assigning `b2 = b1` moves the box.
`Box<dyn Trait>` is a fat pointer
Two words: data and vtable. `Box<T>` for a sized `T` is one word.