Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MEMORY & SHARED OWNERSHIP
BUILD NOTE 38 / 53

Give recursive shapes a fixed-size handle.

Use owned indirection when a value’s layout needs it.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

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.

lessons/box/src/main.rs
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));
}
↳ EXPECTED OUTPUT
sum=7
  1. 1

    Box breaks the infinitely recursive layout.

  2. 2

    The recursive function borrows each node.

  3. 3

    Dropping the owner cleans up its owned boxes.

From the extracted rust-workbench folder
cargo run -p lesson_box

03 Mind the boundary

04 Your next build

A SMALL MISSION

Count nodes in the recursive list and test the empty case.

Reveal one possible solution +
solutions/box/src/main.rs
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

QUICK SIGNAL CHECK

Why does a recursive enum commonly need Box?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.