Skip to main content

Box and recursive types

`Box<T>` puts a value on the heap and keeps a pointer to it on the stack. It is the simplest smart pointer: one owner, freed when the box goes out of scope, no runtime overhead beyond the allocation.

It is required for recursive types. A tree node that contains another node directly would have infinite size, and the compiler says so. A `Box` has a known pointer size, which breaks the cycle.

It is also how you store a trait object (`Box<dyn Trait>`) or return a large value without copying it around.

A type with infinite size

enum Tree {
    Leaf(i32),
    Node(Tree, Tree), // error[E0072]
}

error[E0072]: recursive type `Tree` has infinite size

Wrap the recursive fields in `Box`: `Node(Box<Tree>, Box<Tree>)`. A pointer has a fixed size, so the type does too.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust