Sub topic 15
Recursive enums with Box
What this chapter covers
This chapter assumes you know how to define enums with data-carrying variants and match on them. It also assumes you know basic ownership and references. You will see why an enum that contains itself fails to compile, how Box fixes that, and how to match on boxed values. You will also see when another container is a better choice.
Why a self-containing enum does not compile
Expression trees, linked lists, and JSON-like values are recursive. An Add expression holds two smaller expressions, and each of those can be an Add too. The obvious Rust definition puts the enum directly inside one of its own variants:
Add(Expr, Expr)
The compiler rejects this with error E0072, "recursive type has infinite size". Rust must know the size of every type at compile time so it can reserve stack space. An enum is as large as its largest variant plus a tag that records which variant is active. An Add that holds two Expr values would have to be larger than an Expr, which contains it. The size calculation never ends.
How Box breaks the cycle
Box<T> is a smart pointer that stores a T on the heap. The Box itself is one pointer, so its size is the same whatever T is. Replacing Expr with Box<Expr> inside the variant gives the compiler a finite size to compute. The enum holds two pointers, and the pointed-to data lives elsewhere.
Here is a complete evaluator:
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 noticing:
evaltakes&Expr, somatch euses default binding modes. Every binding is a reference:nis&i64, andaandbare&Box<Expr>.eval(a)passes a&Box<Expr>where a&Expris expected. Deref coercion converts it automatically, becauseBox<T>implementsDeref<Target = T>.- Each
Box::newallocates separately. Building a tree means one heap allocation per node.
Matching through a Box
A pattern cannot look inside a Box directly. Box patterns exist only on unstable Rust. The usual approach is to match the outer variant, then dereference the box when you need the inner value.
- With a reference, write
&**a. The first*strips the reference and the second strips theBox. You can usually avoid this by calling methods or relying on deref coercion. - With an owned value, write
*a. Moving out of aBoxwith*is allowed forBoxand for no other smart pointer. It consumes the box and frees its allocation.
The next program uses the owned form to simplify expressions. It removes additions of zero, multiplications by one or zero, and double negation. It also adds helper constructors, which hide the Box::new noise, and a Display implementation.
use std::fmt;
enum Expr {
Num(i64),
Neg(Box<Expr>),
Add(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
}
impl Expr {
fn num(n: i64) -> Expr {
Expr::Num(n)
}
fn neg(a: Expr) -> Expr {
Expr::Neg(Box::new(a))
}
fn add(a: Expr, b: Expr) -> Expr {
Expr::Add(Box::new(a), Box::new(b))
}
fn mul(a: Expr, b: Expr) -> Expr {
Expr::Mul(Box::new(a), Box::new(b))
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Expr::Num(n) => write!(f, "{n}"),
Expr::Neg(a) => write!(f, "-({a})"),
Expr::Add(a, b) => write!(f, "({a} + {b})"),
Expr::Mul(a, b) => write!(f, "({a} * {b})"),
}
}
}
fn simplify(e: Expr) -> Expr {
match e {
Expr::Add(a, b) => match (simplify(*a), simplify(*b)) {
(Expr::Num(0), other) | (other, Expr::Num(0)) => other,
(x, y) => Expr::add(x, y),
},
Expr::Mul(a, b) => match (simplify(*a), simplify(*b)) {
(Expr::Num(0), _) | (_, Expr::Num(0)) => Expr::Num(0),
(Expr::Num(1), other) | (other, Expr::Num(1)) => other,
(x, y) => Expr::mul(x, y),
},
Expr::Neg(a) => match simplify(*a) {
Expr::Num(n) => Expr::Num(-n),
Expr::Neg(inner) => *inner,
other => Expr::neg(other),
},
num @ Expr::Num(_) => num,
}
}
fn main() {
let e = Expr::add(
Expr::mul(Expr::num(1), Expr::add(Expr::num(0), Expr::num(7))),
Expr::neg(Expr::neg(Expr::num(0))),
);
println!("{e}");
println!("{}", simplify(e));
}The output is:
((1 * (0 + 7)) + -(-(0)))
7Several earlier features appear together here:
- Matching on a tuple of two simplified subtrees lets one arm test both children at once.
- The or-pattern
(Expr::Num(0), other) | (other, Expr::Num(0))bindsotherin both alternatives. Both bindings must have the same name and type. num @ Expr::Num(_)binds the whole value while checking its shape.- The match is exhaustive. If you add a variant to
Expr, the compiler flagssimplify,Display, and every other match that omits it.
Choosing a container for the recursive part
Box is the default, but it is not the only option.
| Container | Use it when | Notes |
|---|---|---|
| `Box<T>` | Each child has exactly one owner | One allocation per node. Cheapest option. |
| `Option<Box<T>>` | A child may be absent, as in a linked list or binary tree | `None` marks the end of the structure. |
| `Vec<T>` | A node has any number of children | `Vec` already stores its items on the heap, so `Call(Vec<Expr>)` needs no `Box`. |
| `Rc<T>` or `Arc<T>` | Several parents share a subtree | Reference-counted. Subtrees are immutable unless you add interior mutability. |
| `&T` | The tree borrows from data owned elsewhere | Adds a lifetime parameter to the enum. |
A related point is that Option<Box<T>> has the same size as Box<T>. A Box is never null, so the compiler uses the null address to represent None.
Gotchas
- Deep trees can overflow the stack. Recursive functions use one stack frame per level. Dropping a very long
Boxchain, such as a linked list with a million nodes, also recurses and can crash. For data that deep, write an iterative loop or a manualDropimplementation. - Allocation cost. Many small
Boxnodes scatter data across the heap. If speed matters, aVec<Node>that refers to children by index is often faster. This is a design choice for later, not a default. - The recursion must go through a pointer. Wrapping only one field in
Boxis enough, but the cycle must pass through aBox,Vec,Rc, or reference.Option<Expr>insideExprstill fails, becauseOptionstores its value inline.
Exercise
Extend the first Expr enum (the one with Num, Add, and Mul) with a Sub(Box<Expr>, Box<Expr>) variant. What does the compiler report for the existing eval function, and what single arm fixes it?
Show answer
The compiler reports error E0004, a non-exhaustive match, because Expr::Sub is not covered. Adding the arm Expr::Sub(a, b) => eval(a) - eval(b), fixes it.
Exercise
Why does enum Call { Op(String, Vec<Call>) } compile without any Box, while enum Call { Op(String, Call) } does not?
Show answer
A Vec stores its elements on the heap and keeps only a fixed-size pointer, length, and capacity inline. The enum therefore has a known size, and the recursion goes through the Vec. In the second definition, Call would contain a Call directly, giving it infinite size.