Smart Pointers · 14 min · free with an account

Box<T>

Lesson preview · about 30%

Box moves a value to the heap behind a single owner.

Core idea

Box gives a recursive or unsized value a known, pointer-sized home.

Start with the idea

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.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Cargo & Real Projects