Sub topic 4
Recursive types: a cons list with Box
This chapter assumes you know Rust enums, pattern matching, and the basic ownership rules. You should also know that values on the stack have a size fixed at compile time. Here you will use Box<T> to define a type that contains itself.
The problem: infinite size
A cons list is a classic recursive structure. Each item holds a value and then another list, or it marks the end. A direct translation into Rust fails:
enum List {
Cons(i32, List),
Nil,
}The compiler reports recursive type List has infinite size. To place a List on the stack, Rust must know its size. A Cons holds an i32 and another List. That inner List could be a Cons holding yet another List, and so on without end, so no finite size exists.
The fix: a pointer with a known size
A Box<T> is a smart pointer that owns a value stored on the heap. The box itself is just a pointer, and its size is the same no matter what it points to. If Cons holds a Box<List>, the size of a List is computable: the largest variant, which is an i32 plus one pointer.
A working cons list
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.
Walk through sum:
match listborrows the list, sovalueis a&i32andrestis a&Box<List>.value + sum(rest)adds the current number to the sum of the tail. Rust acceptsrestwhere a&Listis expected because of deref coercion, which a later chapter covers.Nilends the recursion and returns0.
Ownership of the nodes
The outer Cons owns its box, and that box owns the next Cons, and so on. When list goes out of scope, Rust drops the first node, which drops its box, which frees the next node. The whole chain is freed in order with no manual cleanup.
Common errors
- Forgetting the box. Any recursive field needs indirection.
Option<Box<Node>>is the usual form in structs, whereNoneplays the role ofNil. - Boxing the wrong thing. Writing
Box<Cons(...)>does not work.Boxwraps a type, andCons(...)is a value of the enumList. UseBox::new(Cons(...)). - Expecting sharing. A box has exactly one owner. You cannot let two lists share the same tail with
Box. That limitation motivatesRc<T>later.
Exercise
Why does enum List { Cons(i32, List), Nil } fail to compile, and what single change fixes it?
Show answer
The compiler cannot compute the size of List, because a Cons contains a List, which can contain another Cons, without end. Changing the field to Box<List> fixes it. A Box is a pointer of fixed size, so the size of List is the size of an i32 plus one pointer, and the rest of the list lives on the heap.