Sub topic 15
Recursive enums with Box
This chapter assumes you know how to define enums, write match expressions, and borrow values. It covers why a recursive enum needs Box and how to build and walk one.
Why a recursive enum fails to compile
A recursive enum has a variant that contains the enum itself. An arithmetic expression is a natural example. An expression is either a number, or a sum or product of two smaller expressions.
Suppose you write the variants like this:
enum Expr {
Num(i64),
Add(Expr, Expr),
}The compiler rejects it with "recursive type Expr has infinite size". Rust must know the size of every type at compile time. An Add would hold two Expr values, and each of those could hold two more, so the size has no upper limit.
Box gives the type a known size
Box<T> is a smart pointer that stores its value on the heap. The Box itself is one pointer, and its size does not depend on T. Wrapping the recursive fields in Box breaks the cycle. Add now holds two pointers, so the size of Expr is fixed.
Building and evaluating a tree
Here is a complete program. Each Box::new allocates one child node.
enum Expr {
Num(i64),
Add(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
}
fn eval(e: &Expr) -> i64 {
match e {
Expr::Num(n) => *n,
Expr::Add(a, b) => eval(a) + eval(b),
Expr::Mul(a, b) => eval(a) * eval(b),
}
}
fn main() {
let expr = Expr::Add(
Box::new(Expr::Num(2)),
Box::new(Expr::Mul(Box::new(Expr::Num(3)), Box::new(Expr::Num(4)))),
);
println!("{}", eval(&expr));
}This prints 14.
Three details are worth checking:
evaltakes&Expr, so matching borrows the tree. The bindingsaandbhave type&Box<Expr>.eval(a)passes a&Box<Expr>where&Expris expected. Deref coercion converts it for you.Num(n)bindsnas&i64, so the arm returns*n.
The function is recursive in the same shape as the type. Each variant that contains an Expr leads to a recursive call, and Num is the base case. The exhaustiveness check still applies. If you add a Sub variant and forget its arm, eval stops compiling.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "recursive type has infinite size" | A variant holds the enum directly | Wrap the recursive field in `Box<...>` |
| "expected `Expr`, found `Box<Expr>`" | Passing a box where a plain value is required | Pass a reference, or dereference with `*` |
| "cannot move out of ... which is behind a shared reference" | Matching a borrowed tree and trying to take ownership of a child | Borrow the child, or match the tree by value |
Taking ownership of a child is possible when you own the tree. Dereferencing a box moves its contents out:
enum Expr {
Num(i64),
Neg(Box<Expr>),
}
fn simplify(e: Expr) -> Expr {
match e {
Expr::Neg(inner) => match *inner {
Expr::Neg(x) => *x,
other => Expr::Neg(Box::new(other)),
},
other => other,
}
}
fn main() {
let e = Expr::Neg(Box::new(Expr::Neg(Box::new(Expr::Num(5)))));
match simplify(e) {
Expr::Num(n) => println!("{n}"),
Expr::Neg(_) => println!("negated"),
}
}The function removes a double negation, so the program prints 5. Here *inner moves the Expr out of the box, so the inner match can take x by value.
Cost
Each Box::new is a heap allocation, and walking the tree follows pointers. This is fine for syntax trees, linked lists, and similar structures. For very deep trees, plain recursion can overflow the stack, so deep structures sometimes need an iterative traversal.
Exercise
Why does enum List { Cons(i32, List), Nil } fail to compile, and what is the smallest change that fixes it?
Show answer
Cons holds a List directly, so a List would contain a List that contains a List, and so on. The compiler cannot compute a finite size. Change the field to Cons(i32, Box<List>). The box is a fixed-size pointer to a heap value, so the size is known.
Exercise
Add a Neg(Box<Expr>) variant to the Expr enum used in eval. What must you change in eval, and why?
Show answer
Add the arm Expr::Neg(a) => -eval(a). match must cover every variant, so without that arm the compiler reports a non-exhaustive match.