Box
What you'll learn:
- put a value on the heap with
Boxand explain why a recursive type needs it; - give one value several owners with
Rcand read the reference count; - change a value inside a
RefCelland explain why its rules are checked at run time.

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.
enum List {
Cons(i32, List), // ✗
Nil,
}
fn main() {
let list = List::Cons(7, List::Nil);
if let List::Cons(n, _) = list {
println!("{n}");
}
}error[E0072]: recursive type `List` has infinite sizeThe 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:
- The
Consvariant holds ani32and a wholeList. - That
Listcan again be aConswith one moreListinside. - 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.
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:
Box::new(5)puts the number5on the heap, andbkeeps the address.*bfollows the address to the value itself, like dereferencing a reference, and*b + 1gives6.Box::new(String::from("locker"))puts a string in a locker.t.len()calls aStringmethod right through theBoxand prints6.show(&t)passes a&Box<String>where a&stris expected, and it works.let u = t;moves the key: nowuowns the locker, andtcan 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.
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:
- The size of
Box<List>is known — it is an address. So the size ofConsis now finite: ani32plus an address. mainbuilds a chain: the first node holds1and the key to the locker with the second node, and the second holds2and the key toNil.sumtakes the list apart withmatch. In theConsarm,restis a&Box<List>reference.sum(rest)is a call to the same functionsumfor the rest of the list: it takesrestas a&Listthrough the same conversion.- A function that calls itself is called recursive. The calls follow the keys down to
Nil, wheresumreturns0; then each call adds its ownn:2 + 0, then1 + 2. It prints3.
Why do you need Box? Interviewers like to ask this. Three typical answers:
- a recursive type, such as
Listor a tree node; - a large value that is moved often: moving a
Boxcopies only the address; - values of different types with one trait in one variable or vector: their sizes differ, but a
Boxalways has one size, an address. That is howBox<dyn Error>works for errors.
Common mistake
A value in a Box was compared with a number directly:
fn main() {
let b = Box::new(5);
if b == 5 { // ✗
println!("five");
}
}error[E0308]: mismatched typesThe 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; aBoxholds only the address, and it has one owner.- A
Boxbehaves like a reference thanks toDerefand frees the locker when it goes out of scope thanks toDrop. - 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>).