Box<T>

Box<T> in Rust: The plan chest in the corner holds drawings of every size -- A0 site plans rolled up, A4 details, a wiring diagram on tracing paper that is…

The Analogy: The Drawing Register On The Wall

The plan chest in the corner holds drawings of every size -- A0 site plans rolled up, A4 details, a wiring diagram on tracing paper that is nearly as long as the room. The register hangs on the wall beside it, and it has one line per drawing: a number, a title, a drawer. You carry the register into meetings. Nobody has ever carried the chest.

Every line in that register is exactly the same width, and that is what makes the register possible at all. If each line held the drawing itself the register would be as tall as the whole archive and no wall would take it. The width of a line does not depend in any way on the size of the drawing it names, and that independence is the entire trick.

It also means a line does not care what kind of drawing sits behind it. A foundation plan, a north elevation and a wiring diagram are wildly different objects on wildly different paper, and all three appear in the register as one line of identical width. You cannot tell from the register what you are about to unroll, and for the purpose of carrying the register about, you do not need to.

And there is exactly one line per drawing, with one drawer number on it. Cross a line out and the drawing behind it is scrapped -- that is what the crossing-out means. If two lines were allowed to name the same drawer, the second person to cross a line out would be scrapping something that had already gone, and the register would stop being worth hanging on a wall.


Syntax or Core Structure

Box::new puts a value on the heap and hands you an owner of it:

fn main() {
    let on_stack = 42u64;
    let on_heap: Box<u64> = Box::new(42);

    println!("{on_stack} {on_heap}");
    println!("{}", *on_heap + 1);

    let doubled = *on_heap * 2;

    println!("{doubled}");

    println!("u64             {}", std::mem::size_of::<u64>());
    println!("[u8; 4096]      {}", std::mem::size_of::<[u8; 4096]>());
    println!("Box<u64>        {}", std::mem::size_of::<Box<u64>>());
    println!("Box<[u8; 4096]> {}", std::mem::size_of::<Box<[u8; 4096]>>());
}

Output:

42 42
43
84
u64             8
[u8; 4096]      4096
Box<u64>        8
Box<[u8; 4096]> 8

The last four figures are for a 64-bit target, where a pointer is eight bytes; on a 32-bit target the three 8s would read 4 and the 4096 would not change. That is the point of the block rather than a detail of it: the array costs 4096 bytes wherever it is written down, and the Box costs the width of one register line no matter what is in the drawer.

Box<T> is an owner, not a borrow. There is exactly one of it, it is dropped at the end of its scope, and dropping it frees the heap allocation as well. Everything else about it is designed to stay out of your way:

PropertyT written down directlyBox<T>
Where the value livesIn the stack frame or the enclosing structOn the heap
Size of the binding itselfThe size of TOne pointer, whatever T is
Cost of a moveCopies T byte for byteCopies one pointer
Owners at any one timeOneOne
Freed whenThe scope endsThe Box is dropped
Needs T's size known at compile timeYesNo

That last row is the whole reason Box exists, and it buys two specific things that nothing else does.


Technical Depth: The Two Jobs Only A Box Can Do

A type that contains itself

enum Leg {
    End,
    Hop(u32, Box<Leg>),
}

fn total(leg: &Leg) -> u32 {
    match leg {
        Leg::End => 0,
        Leg::Hop(km, rest) => km + total(rest),
    }
}

fn legs(leg: &Leg) -> u32 {
    match leg {
        Leg::End => 0,
        Leg::Hop(_, rest) => 1 + legs(rest),
    }
}

fn main() {
    let route = Leg::Hop(12, Box::new(Leg::Hop(31, Box::new(Leg::Hop(7, Box::new(Leg::End))))));

    println!("legs {}", legs(&route));
    println!("km   {}", total(&route));
}

Output:

legs 3
km   50

Write Hop(u32, Leg) instead and the compiler refuses with error[E0072]: recursive type \Leg\ has infinite size, followed by a help line that names the cure: insert some indirection, such as a Box, Rc, or &, to break the cycle. The reasoning is worth following rather than memorising. To lay out Leg, the compiler needs the size of its largest variant; that variant contains a Leg, whose size needs the size of its largest variant, and there is no bottom to the regress. Box<Leg> is one pointer wide regardless, so the question terminates immediately and every Leg value is small and fixed-size no matter how long the route.

Notice total(rest) passing a &Box<Leg> to a function that takes &Leg. Deref coercion does that silently, which is why almost no code ever needs to mention Box in a signature.

A type not known until run time

trait Charge {
    fn label(&self) -> &str;
    fn pence(&self, minutes: u32) -> u32;
}

struct Flat {
    rate: u32,
}

struct Tiered {
    rate: u32,
    cap: u32,
}

impl Charge for Flat {
    fn label(&self) -> &str {
        "flat"
    }

    fn pence(&self, minutes: u32) -> u32 {
        minutes * self.rate
    }
}

impl Charge for Tiered {
    fn label(&self) -> &str {
        "tiered"
    }

    fn pence(&self, minutes: u32) -> u32 {
        let charged = if minutes > self.cap { self.cap } else { minutes };

        charged * self.rate
    }
}

fn main() {
    let book: Vec<Box<dyn Charge>> = vec![
        Box::new(Flat { rate: 4 }),
        Box::new(Tiered { rate: 6, cap: 60 }),
    ];

    for tariff in &book {
        println!("{:7} {:5} {:5}", tariff.label(), tariff.pence(30), tariff.pence(90));
    }

    println!("Box<dyn Charge> {}", std::mem::size_of::<Box<dyn Charge>>());
}

Output:

flat      120   360
tiered   180   360
Box<dyn Charge> 16

Flat and Tiered are different sizes and different types, and they sit in one Vec because what the Vec actually holds is two register lines. dyn Charge means "some type implementing Charge, decided at run time", and it is unsized -- writing Vec<dyn Charge> earns error[E0277]: the size for values of type \dyn Charge\ cannot be known at compilation time. The Box is what makes it storable.

Sixteen, not eight, and that is not a mistake. A Box<dyn Trait> is a fat pointer: one word to the value and one word to its vtable, the little table of function addresses that lets tariff.pence(30) find the right pence at run time. A Box<Flat> would be eight; the extra word is the price of not knowing.

impl Charge in a parameterBox<dyn Charge>
Which implementation runs is decidedAt compile time, one machine-code copy per typeAt run time, through the vtable
Different types in one collectionImpossibleThe point of it
Indirection per callNoneOne pointer hop, then one vtable lookup
Size known at compile timeYesOnly because of the Box
Can be inlinedOftenGenerally not

This is also the answer to the question the closures lesson left open. A price book of twenty tariffs cannot be a Vec of closures, because every closure has its own anonymous type -- but it can be this:

fn main() {
    let step = 5;

    let book: Vec<Box<dyn Fn(u32) -> u32>> = vec![
        Box::new(|n| n + 1),
        Box::new(move |n| n + step),
        Box::new(|n| n * 2),
    ];

    for (i, f) in book.iter().enumerate() {
        println!("f{i}(10) = {}", f(10));
    }
}

Output:

f0(10) = 11
f1(10) = 15
f2(10) = 20

Getting at what is inside

fn main() {
    let boxed = Box::new(String::from("north gate"));

    println!("{}", boxed.len());
    println!("{}", boxed.to_uppercase());

    let owned: String = *boxed;

    println!("{owned}");

    let big = Box::new([0u8; 4096]);
    let moved = big;

    println!("{}", moved.len());
}

Output:

10
NORTH GATE
north gate
4096

Method calls go straight through: boxed.len() reaches String and then str without a single explicit *, because Box<T> implements Deref with Target = T. *boxed moves the String out and leaves the Box consumed, which Box is uniquely allowed to do -- no other smart pointer in std lets you move its contents out with *.

And let moved = big; copied eight bytes. The array behind it did not move at all. Handing a large value around by Box rather than by value is the one performance argument for boxing that actually holds up, and it holds up only when the value is genuinely large.


Real World Example: A Price Book That Is Data Rather Than Code

A tariff is not really a function. It is a small tree -- a fixed fee plus a capped per-minute rate, or whichever of two amounts is larger -- and a tree of that shape is a recursive type, so every branch is a Box:

enum Rule {
    Fixed(u32),
    PerMinute(u32),
    Sum(Box<Rule>, Box<Rule>),
    Capped(Box<Rule>, u32),
    Greater(Box<Rule>, Box<Rule>),
}

fn pence(rule: &Rule, minutes: u32) -> u32 {
    match rule {
        Rule::Fixed(p) => *p,
        Rule::PerMinute(p) => p * minutes,
        Rule::Sum(a, b) => pence(a, minutes) + pence(b, minutes),
        Rule::Capped(inner, cap) => {
            let raw = pence(inner, minutes);

            if raw > *cap {
                *cap
            } else {
                raw
            }
        }
        Rule::Greater(a, b) => {
            let x = pence(a, minutes);
            let y = pence(b, minutes);

            if x > y {
                x
            } else {
                y
            }
        }
    }
}

fn describe(rule: &Rule) -> String {
    match rule {
        Rule::Fixed(p) => format!("{p}"),
        Rule::PerMinute(p) => format!("{p}/min"),
        Rule::Sum(a, b) => format!("({} + {})", describe(a), describe(b)),
        Rule::Capped(inner, cap) => format!("min({}, {cap})", describe(inner)),
        Rule::Greater(a, b) => format!("max({}, {})", describe(a), describe(b)),
    }
}

fn nodes(rule: &Rule) -> u32 {
    match rule {
        Rule::Fixed(_) | Rule::PerMinute(_) => 1,
        Rule::Sum(a, b) | Rule::Greater(a, b) => 1 + nodes(a) + nodes(b),
        Rule::Capped(inner, _) => 1 + nodes(inner),
    }
}

fn main() {
    let book: Vec<(&str, Rule)> = vec![
        ("simple", Rule::PerMinute(4)),
        (
            "standard",
            Rule::Sum(
                Box::new(Rule::Fixed(150)),
                Box::new(Rule::Capped(Box::new(Rule::PerMinute(6)), 300)),
            ),
        ),
        (
            "floor",
            Rule::Greater(Box::new(Rule::Fixed(500)), Box::new(Rule::PerMinute(9))),
        ),
    ];

    for (name, rule) in &book {
        println!("{name:9} {:2} nodes  {}", nodes(rule), describe(rule));
    }

    for minutes in [10u32, 30, 90] {
        println!("{minutes:3} min");

        for (name, rule) in &book {
            println!("  {name:9} {:5}", pence(rule, minutes));
        }
    }
}

Output:

simple     1 nodes  4/min
standard   4 nodes  (150 + min(6/min, 300))
floor      3 nodes  max(500, 9/min)
 10 min
  simple      40
  standard   210
  floor      500
 30 min
  simple     120
  standard   330
  floor      500
 90 min
  simple     360
  standard   450
  floor      810

Three functions walk the same tree and none of them knows its shape in advance: one prices it, one prints it, one counts it. The tree could not exist at all without Box, because Rule contains Rule; with the Box every Rule value is a small fixed-size thing regardless of how much hangs off it, which is why the Vec can hold three trees of three different shapes side by side.

The reason to build it this way is that the tariffs are now data. A new one is a new tree, assembled at run time from a config file or a database row, and pence never changes. Compare this with the closures lesson, where a tariff was a closure and the same billing loop worked perfectly well: a closure cannot be printed, counted, serialised or inspected, and describe is precisely the function you cannot write for one. The tree gives all of that up in exchange for nothing -- pence is still a single recursive walk.

Single ownership is doing quiet work here too. Each Box belongs to exactly the node holding it, so dropping the root drops the whole tree once, in one pass, with no counting and no possibility of freeing a node twice. It is also the limitation: two Sum nodes cannot both point at the same Capped subtree, because that would be two register lines naming one drawer. Sharing a subtree means cloning it, and the next lesson's Rc<T> is what changes that rule.

The honest limits. pence, describe and nodes all recurse, so a pathologically deep tree overflows the stack -- and so does dropping it, since Box's destructor is recursive as well, which is a genuinely surprising way for a program to die on input it accepted happily. A parser that builds these from untrusted text needs a depth limit, and an evaluator for deep trees needs flattening into a loop with an explicit stack. describe allocates a String at every node and discards all but the outermost, which is fine at four nodes and wasteful at four thousand; passing a &mut String down instead would allocate once. Every amount is a bare u32 of pence with no currency attached and no overflow check, so a long enough session in release mode wraps silently. And nothing validates a tree: Capped(Fixed(500), 100) is a perfectly constructible rule that ignores its own input and always charges 100, and no part of this code will tell you so.


Common Mistakes

  1. Boxing to make things faster. For a u64, an i32 or a small struct, Box adds an allocation, a free and a pointer hop and removes any chance of the value living in a register. It is slower, and the gap widens the more often you touch the value.
  1. Meeting E0072 and not reading the help line. recursive type has infinite size names the fix in the text immediately below it. The instinct to restructure the whole data model is almost always wrong; the answer is a Box on the recursive field.
  1. Writing Vec<dyn Trait>. dyn Trait has no size, so it cannot be an element of anything. Vec<Box<dyn Trait>> is the storable form, and &dyn Trait is the borrowed one.
  1. Boxing in order to pass to a function. If the function only reads the value, it wants &T. Allocating a Box to hand something over and dropping it immediately afterwards is pure overhead.
  1. Assuming Box<dyn Trait> is one pointer wide. It is two: the value and the vtable. Code that assumes a pointer-sized handle -- and any FFI signature written on that assumption -- is wrong.
  1. The pointless round trip. *Box::new(x) is x with an allocation in the middle, and it appears surprisingly often in code that was refactored halfway.
  1. Expecting a Box to be shareable. One owner, always. Cloning a Box deep-copies the value behind it, which is correct but is not sharing, and the moment you find yourself cloning a large subtree to give two parents a copy, you want Rc.
  1. Ignoring recursive drop. A boxed list a million nodes long is built without complaint and then blows the stack when it goes out of scope, in a destructor, where the failure is hardest to read.
  1. Boxing every field for consistency. Six boxed fields is six allocations scattered across the heap where one plain struct would have been a single contiguous piece of memory. Box the one field that needs it.

Best Practices

  • Box for the two reasons that genuinely require it: breaking a recursive type, and holding a value whose concrete type is not known until run time. Those two cover nearly every honest use.
  • Prefer impl Trait while one concrete type per call site is enough, and move to Box<dyn Trait> at the exact point where you need several different types in one place. Going dyn earlier costs speed for nothing.
  • Take &T in function signatures and let deref coercion handle callers who hold a Box<T>. A signature that says &Box<T> has leaked a storage decision into an interface.
  • Box the large or variably sized field rather than wrapping the whole struct, so the rest of it stays contiguous.
  • Put a depth limit on anything that builds a recursive structure from input you did not write, and remember the limit protects the destructor as much as the parser.
  • Flatten to a loop with an explicit stack when depth is unbounded. Recursion is the right first version and the wrong last one.
  • Keep Box<dyn Error> for error paths where the caller only reports, and a concrete enum where the caller must branch -- the same trade as here, in the shape Module 5 introduced.
  • Measure before boxing for performance, and be suspicious of the result if the value is under a few hundred bytes.

Practice Exercises

  1. Write the Leg enum with Hop(u32, Leg) and no Box, compile it, and copy out both the error code and the help line underneath. Then add the Box and confirm the same total function works unchanged.
  1. Add a Discount(Box<Rule>, u32) variant to the price book that takes a percentage off whatever is inside it, and update all three walkers. Deliberately forget one of them first, and note exactly what the compiler says -- this is the payoff for matching exhaustively instead of using a catch-all.
  1. Build a Vec<Box<dyn Charge>> with three implementors and print each one's charge at two durations. Then change the type to Vec<dyn Charge>, record the error code and message, and explain in one sentence what the Box was providing.
  1. Rewrite describe to append into a single &mut String passed down through the recursion instead of returning a new String at every node. Count how many allocations the standard tree needed before and after.