Box<T> for heap allocation and recursive types

Marcus Chen Jan 2026
1 tab
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
}
1 file · rust Explain with highlit

Box<T> is Rust's simplest smart pointer: it allocates T on the heap and gives you ownership. When the Box goes out of scope, the heap memory is freed. I use Box when I need indirection (like recursive types), when moving large structs is expensive, or when I want trait objects (Box<dyn Trait>). The size of a Box is one pointer, making it cheap to move. For recursive data structures like trees or linked lists, Box is essential because the compiler needs a known size. It's also useful for abstracting over types with Box<dyn Error> or Box<dyn Iterator>. Unlike reference counting, Box has zero runtime overhead beyond the allocation itself.