Sub topic 4
Recursive types: a cons list with Box
This chapter assumes you know Rust enums, pattern matching, and the difference between stack and heap memory. You should also know that Box<T> stores a value on the heap and that the owner of the box frees it. Here you will use Box to solve a concrete compiler error: a type that contains itself.
The problem: a type of unknown size
Rust must know how many bytes every type takes on the stack. Most types satisfy this easily. A recursive type is a type that contains a value of its own type. It can break the rule.
The classic example is the cons list, which comes from Lisp. Each item holds a value and the rest of the list. The list ends with a special empty marker. In Rust that suggests this enum:
enum List {
Cons(i32, List),
Nil,
}The compiler rejects it:
error[E0072]: recursive type `List` has infinite size
--> src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
2 | Cons(i32, List),
| ---- recursive without indirectionTo compute the size of List, the compiler needs the size of its largest variant. Cons holds an i32 and a List. The size of that List depends on Cons again, and so on without end. No finite answer exists.
The fix: indirection with Box
The error message says "recursive without indirection". Indirection means storing a pointer to the value instead of the value itself. A pointer has a fixed size no matter what it points to. Box<T> is the simplest owning pointer, so you wrap the recursive field in it:
use List::{Cons, Nil};
enum List {
Cons(i32, Box<List>),
Nil,
}
fn sum(list: &List) -> i32 {
match list {
Cons(value, rest) => value + sum(rest),
Nil => 0,
}
}
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("sum = {}", sum(&list));
}The program prints sum = 6.
Now the size calculation ends. Cons needs room for an i32 and a pointer. Nil needs no data. The enum is as big as its largest variant plus any tag it needs. Each Box::new call puts the next node on the heap, and the previous node stores only the address.
The use List::{Cons, Nil}; line at the top brings the variants into scope, so you can write Cons(...) instead of List::Cons(...). Rust allows the use to appear before the enum it names.
What the memory looks like
The first node lives on the stack, in the variable list. Every later node is a separate heap allocation.
You can confirm that the box is only a pointer. This program compares its size with a machine word:
use std::mem::size_of;
enum List {
Cons(i32, Box<List>),
Nil,
}
fn main() {
assert_eq!(size_of::<Box<List>>(), size_of::<usize>());
println!("a Box<List> is {} bytes", size_of::<Box<List>>());
}On a 64-bit machine it prints a Box<List> is 8 bytes. That size is the same whether the list has one element or a million.
How the recursion in sum works
sum takes &List, so it borrows the list and does not consume it. Inside the match, default binding modes turn the pattern Cons(value, rest) into references. That gives value: &i32 and rest: &Box<List>.
Two details are worth noticing:
value + sum(rest)adds a&i32to ani32. Rust implementsAddfor that combination, so it compiles without a manual dereference.sum(rest)passes a&Box<List>where a&Listis expected. This works through deref coercion, which a later chapter covers. For now, read it as "a reference to a box can be used where a reference to its contents is expected".
The Nil arm is the base case. Without it the recursion would never stop.
Option<Box<T>> as the end marker
Many Rust programs do not define a Nil variant. They use Option to mean "there may be a next node":
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn len(mut current: Option<&Node>) -> usize {
let mut count = 0;
while let Some(node) = current {
count += 1;
current = node.next.as_deref();
}
count
}
fn main() {
let list = Node {
value: 1,
next: Some(Box::new(Node {
value: 2,
next: Some(Box::new(Node { value: 3, next: None })),
})),
};
println!("first = {}, len = {}", list.value, len(Some(&list)));
}This prints first = 1, len = 3. The as_deref method turns &Option<Box<Node>> into Option<&Node>. It lets the loop walk the list without moving anything and without recursion.
The same shape works for binary trees. Use two fields, left: Option<Box<Node>> and right: Option<Box<Node>>.
Edge cases and common errors
Four problems come up often with recursive types.
- Wrapping the wrong thing.
Boxmust sit on the recursive field. Boxing the whole enum, as inBox<List>at the top level, does not fix the definition. - Using a plain reference. Writing
Cons(i32, &List)compiles only if you add a lifetime, and then something else must own the next node. ABoxmakes the node own the rest of the list, which is usually what you want. - Mutating through the box. A
Boxowns its contents, so&mut Listgives you full mutable access down the chain. You can reassign a tail with*rest = Box::new(Nil)when you hold a mutable reference. - Stack overflow on long lists. A cons list drops its nodes recursively. Each
Boxfrees its child, and that frees its child, and so on. A list with hundreds of thousands of nodes can overflow the stack when it is dropped.
Trade-offs of boxing
Each node costs one heap allocation. Allocation takes time, and nodes scattered across memory are slower to traverse than an array because they cache poorly. In return you get a type of known size, with a clear owner at every node. The compiler frees the whole structure when the head goes out of scope.
Exercise
A colleague writes enum Tree { Leaf(i32), Branch(Tree, Tree) } and gets error E0072. Rewrite the definition so it compiles, and explain why the original had no finite size.
Show answer
Use enum Tree { Leaf(i32), Branch(Box<Tree>, Box<Tree>) }. In the original, a Branch contained two Trees by value, and each of those could be a Branch containing two more, so the size calculation never ended. Box stores only a fixed-size pointer to each child, so Branch needs the size of two pointers and the compiler can compute a finite size.
Exercise
Using the first List definition, write fn len(list: &List) -> usize that returns the number of Cons nodes. What does it return for the list built in main?
Show answer
fn len(list: &List) -> usize { match list { Cons(_, rest) => 1 + len(rest), Nil => 0 } }. For Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))) it returns 3, because there are three Cons nodes and Nil adds nothing.