Skip to content
Theory · Smart pointers · lesson 1 of 6

Box

What you'll learn

What you'll learn:

  • put a value on the heap with Box and explain why a recursive type needs it;
  • give one value several owners with Rc and read the reference count;
  • change a value inside a RefCell and explain why its rules are checked at run time.
A key Box<List> leads to a warehouse cell with a tile and a second key, which leads to a cell holding a card Nil

Remember the stack and the heap from the ownership theme? The stack holds values whose size is known in advance. Everything else goes to the heap, and the stack keeps its address — that is how String works.

Picture a big warehouse with lockers. You put a thing in a locker and get a key. The key is small and fits in your pocket, while the thing in the locker can be anything. When the key's holder leaves, the locker is emptied.

Why would a program want such a key? Let's describe a list of numbers the way you would on paper: a list is either nothing, or a number followed by the rest of the list.

Rust
enum List {
    Cons(i32, List), // ✗
    Nil,
}

fn main() {
    let list = List::Cons(7, List::Nil);
    if let List::Cons(n, _) = list {
        println!("{n}");
    }
}
TEXT
error[E0072]: recursive type `List` has infinite size

The program does not compile. The compiler must know the size of every type at build time to set aside room for a value. Let's count the size of List:

  1. The Cons variant holds an i32 and a whole List.
  2. That List can again be a Cons with one more List inside.
  3. The type contains itself, and the sum never ends: the size is infinite.

The Nil variant does not help here. It ends the chain of values, but the compiler counts the size of the type, not of a particular value.

This is a hard build error, not a warning. The program never even starts, so there is no stack overflow at run time. In its hint the compiler suggests breaking the cycle with a pointer, such as Box.

A key to a locker

Box::new(x) puts the value x on the heap and returns a Box — the key to that locker. The Box itself is small: it holds only the address.

Rust
fn show(s: &str) {
    println!("{s}");
}

fn main() {
    let b = Box::new(5);
    println!("{}", *b + 1); // 6
    let t = Box::new(String::from("locker"));
    println!("{}", t.len()); // 6
    show(&t); // locker
    let u = t;
    show(&u); // locker
}

Let's walk through the example line by line:

  1. Box::new(5) puts the number 5 on the heap, and b keeps the address.
  2. *b follows the address to the value itself, like dereferencing a reference, and *b + 1 gives 6.
  3. Box::new(String::from("locker")) puts a string in a locker.
  4. t.len() calls a String method right through the Box and prints 6.
  5. show(&t) passes a &Box<String> where a &str is expected, and it works.
  6. let u = t; moves the key: now u owns the locker, and t can no longer be used.

A Box has one owner, like a String. When u goes out of scope, the Box frees the locker on the heap.

Box behaves like a reference

Why do t.len() and show(&t) from items 4 and 5 work? Box has an implementation of the Deref trait. It tells the compiler how to get from the Box to the value inside. That is why *b works, and why the compiler finds the len method through the wrapper.

For the same reason &Box<String> turns into &String and then into &str. It is the same conversion that lets a &String fit a &str parameter.

A smart pointer is a type that holds the address of a value, behaves like a reference thanks to Deref, and cleans up after itself thanks to the Drop trait. The code in Drop runs when the owner goes out of scope; for a Box, it frees the locker. Box is the simplest of them: no counters and no checks, only the address.

Here the warehouse picture parts with real life. A real key can be taken to a locksmith and copied, but a Box has no copies. clone on a Box builds a second locker with a copy of the value, and each locker has its own key.

A list with Box

Back to the list. Cons now holds not a List itself but a Box<List> — the key to the locker with the rest of the list.

Rust
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn sum(list: &List) -> i32 {
    match list {
        List::Cons(n, rest) => n + sum(rest),
        List::Nil => 0,
    }
}
fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{}", sum(&list)); // 3
}

Let's go step by step:

  1. The size of Box<List> is known — it is an address. So the size of Cons is now finite: an i32 plus an address.
  2. main builds a chain: the first node holds 1 and the key to the locker with the second node, and the second holds 2 and the key to Nil.
  3. sum takes the list apart with match. In the Cons arm, rest is a &Box<List> reference. sum(rest) is a call to the same function sum for the rest of the list: it takes rest as a &List through the same conversion.
  4. A function that calls itself is called recursive. The calls follow the keys down to Nil, where sum returns 0; then each call adds its own n: 2 + 0, then 1 + 2. It prints 3.

Why do you need Box? Interviewers like to ask this. Three typical answers:

  • a recursive type, such as List or a tree node;
  • a large value that is moved often: moving a Box copies only the address;
  • values of different types with one trait in one variable or vector: their sizes differ, but a Box always has one size, an address. That is how Box<dyn Error> works for errors.

Common mistake

A value in a Box was compared with a number directly:

Rust
fn main() {
    let b = Box::new(5);
    if b == 5 { // ✗
        println!("five");
    }
}
TEXT
error[E0308]: mismatched types

The program does not compile. b is a key of type Box<i32>, while 5 is an i32 number, and == does not compare values of different types. To compare what is in the locker, you have to reach it: *b == 5.

Key points

  • Box::new(x) puts a value on the heap; a Box holds only the address, and it has one owner.
  • A Box behaves like a reference thanks to Deref and frees the locker when it goes out of scope thanks to Drop.
  • A type that holds itself has an infinite size: that is build error E0072, not a panic.
  • A recursive type is cured with a pointer: Cons(i32, Box<List>).