
Understand it
A recursive type has no fixed size, because each level would contain another whole level. Box has a known pointer size, so putting the recursive part behind one makes the type representable. Box also lets a function return a trait object whose concrete size is not known at the call site.
A recursive enum needs a known size at compile time. If Tree::Node directly contained two more Tree values, each of those nodes would contain more nodes with no finite size the compiler could lay out. Box<Tree> replaces each child with a pointer whose size is known. The actual child values live in separate heap allocations, and the boxes own them. Dropping the root recursively drops the owned children.
The sample's sum function borrows &Tree, matches on its variants, and reads through the boxes. It does not take ownership of the tree just to traverse it. Trace a root with two leaves and predict the sum before running the code. Then add one nested node and observe how the recursive call follows a box. This exercise shows the separation between the size of the enum variant and the depth of the runtime tree.
A box is also a way to own a value whose concrete type is hidden behind a trait object, Box<dyn Trait>. The box does not make every operation faster: following pointers and allocating each node can cost more than a compact flat representation. Use it when indirection expresses a real need, such as recursion or owned dynamic dispatch. For a simple fixed set of values, a Vec<T> or plain struct may be clearer. Choose the data shape first, then the pointer type that makes it representable.
The box is an owning pointer, so moving the box moves ownership of the child allocation without copying the entire tree. That makes recursive construction manageable while preserving deterministic cleanup.
Read the code
enum Tree {
Leaf(i32),
Node(Box<Tree>, Box<Tree>),
}
fn sum(tree: &Tree) -> i32 {
match tree {
Tree::Leaf(value) => *value,
Tree::Node(l, r) => sum(l) + sum(r),
}
}Without Box, this enum would need infinite size.
Practice starter
enum List {
Cons(i32, List),
Nil,
}Try it
Define a recursive type and total its values.
What success looks like: It compiles, and you can explain why Box is required.
Check your understanding
Why does that recursive enum fail to compile?
Reveal the answer
- An enum can never refer to itself, boxed or not
- The type would have infinite size without an indirection
- An i32 payload is not allowed inside an enum
Box<List> makes the recursive field pointer-sized and the type finite.
Go deeper
Common misconception: “An enum can never refer to itself, even through a Box.”
An enum can contain itself through a pointer. Box gives a recursive or unsized value a known-size home, so the type stops being infinitely large.
- Size the enum:
Tree::Nodeholds twoBox<Tree>fields, each one pointer, soTreehas a fixed size however deep a tree gets. - Match the variant:
sumborrows&Tree, somatchbindsvalueto&i32andlandrto&Box<Tree>; nothing is moved out. - Follow the boxes:
sum(l)passes&Box<Tree>, and deref coercion turns it into&Tree. Leaves return*value, so aNodeover leaves 1 and 2 totals 3.
Transfer challenge: Fix the practice's List with Box<List> and write a total function for it. Then predict size_of::<List>() compared with size_of::<Box<List>>() and print both.
Connections
- Workspaces: Many crates, one lockfile
- Rc & RefCell: Shared ownership and interior mutability
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Box<T> (courseId "projects", lessonId "box") Link: https://crabrix.com/learn/projects/box/ Goal: Box gives a recursive or unsized value a known-size home. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/box) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.