Box for Heap Allocation

Updated

October 31, 2026

Box for Heap Allocation

Box<T> allocates a value on the heap and provides a stack pointer with ownership semantics.

fn main() {
    let b = Box::new(42);
    println!("Box points to heap value: {}", *b);

    // Recursive data types require Box to have a known size:
    #[derive(Debug)]
    enum List {
        Cons(i32, Box<List>),
        Nil,
    }

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