How to Use Box<T> for Heap Allocation in Rust

Use Box::new(value) to allocate data on the heap for recursive types or large data transfers.

Use Box<T> to allocate data on the heap by wrapping a value with Box::new(value). This stores the pointer on the stack while the actual data resides on the heap, allowing for recursive types or transferring large data without copying.

fn main() {
    let b = Box::new(5);
    println!("b = {b}");
}

For recursive types like a linked list node, wrap the inner reference in a Box to give it a known size:

#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{:?}", list);
}