Give recursive shapes a fixed-size handle.
Use owned indirection when a value’s layout needs it.
01 Understand the contract
Box<T> owns a heap-allocated T and provides a fixed-size owning pointer. Recursive types need indirection because a value cannot contain an infinitely large copy of itself. An enum can therefore place its next node behind Box. A boxed allocation is not automatically faster than a value stored directly; it adds indirection and allocation work. Use Vec for ordinary contiguous lists unless a different structure serves the operation you need. Box is also useful for owning trait objects.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
enum List {
Node(i32, Box<List>),
End,
}
fn sum(list: &List) -> i32 {
match list {
List::Node(value, next) => value + sum(next),
List::End => 0,
}
}
fn main() {
let list = List::Node(3, Box::new(List::Node(4, Box::new(List::End))));
println!("sum={}", sum(&list));
}sum=7
- 1
Box breaks the infinitely recursive layout.
- 2
The recursive function borrows each node.
- 3
Dropping the owner cleans up its owned boxes.
cargo run -p lesson_box03 Mind the boundary
04 Your next build
Count nodes in the recursive list and test the empty case.
Reveal one possible solution +
enum List {
Node(Box<List>),
End,
}
fn count(v: &List) -> usize {
match v {
List::Node(next) => 1 + count(next),
List::End => 0,
}
}
fn main() {
assert_eq!(count(&List::End), 0);
assert_eq!(count(&List::Node(Box::new(List::End))), 1);
}05 Check your reasoning
Why does a recursive enum commonly need Box?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.