Enums with Complex Data

Enums with Complex Data in Rust: A freight manifest has one line per item, and every line is the same width.

The Analogy: The Nested Crate Manifest

A freight manifest has one line per item, and every line is the same width. That is not tidiness -- it is what lets the clerk total the sheet without reading it twice, and what lets the printer make the form in the first place. Most lines are simple: a part number and a quantity.

But a crate can contain another crate. If the inner crate's whole manifest were written out inline on the line, the line would stop being a fixed width. And a crate containing a crate containing a crate would need a line of unbounded length -- there is no form you can print that accommodates that, because you would have to know the deepest nesting before you printed the first sheet.

So the manifest does the only thing that works. The line says "crate -- see manifest 7". Fixed width, always, and the nesting lives elsewhere on the pallet. The reference costs one short number whether the inner crate holds two bolts or another forty crates, and the clerk follows it only when they need to.

Rust hits the identical wall for the identical reason. An enum's size is settled at compile time, so a variant holding the enum itself has no finite size to settle on -- the compiler says exactly that, with error[E0072]: recursive type has infinite size, and tells you to insert indirection. A Box<Expr> is "see manifest 7": one pointer, fixed width, any depth. This lesson is about designing those payloads -- when to box, when a Vec has already done it for you, and when a variant's data has grown up enough to deserve a struct of its own.


Syntax or Core Structure

A recursive enum plus the indirection that makes it legal. Expr is a tiny arithmetic tree: a number is a leaf, and every other variant holds one or two Expr values behind a Box.

// Each variant may contain the enum again -- but only behind a Box, which is
// a fixed-size pointer no matter how deep the tree goes.
#[derive(Debug)]
enum Expr {
    Num(f64),
    Neg(Box<Expr>),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
}

fn eval(e: &Expr) -> f64 {
    match e {
        Expr::Num(n) => *n,
        // inner is &Box<Expr>; deref coercion hands eval an &Expr.
        Expr::Neg(inner) => -eval(inner),
        Expr::Add(l, r) => eval(l) + eval(r),
        Expr::Mul(l, r) => eval(l) * eval(r),
    }
}

fn show(e: &Expr) -> String {
    match e {
        Expr::Num(n) => format!("{n}"),
        Expr::Neg(inner) => format!("-({})", show(inner)),
        Expr::Add(l, r) => format!("({} + {})", show(l), show(r)),
        Expr::Mul(l, r) => format!("({} * {})", show(l), show(r)),
    }
}

fn main() {
    // (2 + 3) * -(4)
    let e = Expr::Mul(
        Box::new(Expr::Add(Box::new(Expr::Num(2.0)), Box::new(Expr::Num(3.0)))),
        Box::new(Expr::Neg(Box::new(Expr::Num(4.0)))),
    );

    println!("{}", show(&e));
    println!("= {}", eval(&e));
    println!("size_of::<Box<Expr>>() = {}", std::mem::size_of::<Box<Expr>>());
}

Output:

((2 + 3) * -(4))
= -20
size_of::<Box<Expr>>() = 8

Three things are worth naming in that program. Construction is verbose because every child needs a Box::new -- the indirection is explicit, and Rust will not insert it for you. Pattern matching, by contrast, is not verbose at all: Expr::Neg(inner) binds inner as &Box<Expr>, and passing it to a function expecting &Expr works because deref coercion applies at the argument position. And the last line is the point of the whole design: a child costs eight bytes on a 64-bit target regardless of whether it is a single number or a thousand-node tree.

Take the Box away and the type stops existing:

enum Expr {
    Num(f64),
    Add(Expr, Expr),
}

Output:

error[E0072]: recursive type `Expr` has infinite size
 --> src/main.rs:1:1
  |
1 | enum Expr {
  | ^^^^^^^^^
2 |     Num(f64),
3 |     Add(Expr, Expr),
  |         ----  ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle

Read the error as arithmetic. To lay out Expr the compiler needs the size of its largest variant; the largest variant is Add, whose size is twice the size of Expr; so the size of Expr is at least twice the size of Expr. Nothing finite satisfies that. rustc also prints the suggested rewrite as a diff, wrapping each field in Box<...>, which has been trimmed here.


Technical Depth: Designing the Payload

Choosing the indirection

Box is the default answer to E0072, but it is not the only one, and quite often the container you already wanted supplies the indirection for free.

WrapperSize of the handleAllocationsReach for it when
Box<T>8 bytesone, per childexactly one child, one owner
Vec<T>24 bytesone, for all childrena variable number of children
Rc<T>8 bytesone, plus two countersseveral parents share one child
&'a T8 bytesnonethe child is owned elsewhere and outlives the enum
Box<[T]>16 bytesone, fixed lengthchildren are fixed once built

The row that saves the most typing is Vec<T>. A Vec is already a fixed-size handle -- a pointer, a length and a capacity -- pointing at a heap buffer, so a variant like List(Vec<Json>) compiles without any Box at all. Writing List(Vec<Box<Json>>) would add a second heap allocation per element and buy nothing.

Generic enums

A variant's payload can be a type parameter, which is how the standard library's most-used enums are built. There is nothing special about Option; you could write it yourself in three lines.

enum Maybe<T> {
    Nothing,
    Just(T),
}

enum Either<L, R> {
    Left(L),
    Right(R),
}

// A generic recursive type: both features at once.
#[derive(Debug)]
enum Tree<T> {
    Leaf,
    Node(Box<Tree<T>>, T, Box<Tree<T>>),
}

Both parameters of Either<L, R> belong to the type, not to the variant, even though any single value only ever fills one of them. That is why Either<String, u8> and Either<u8, String> are unrelated types that cannot be assigned to one another.

Standard-library enumVariantsWhat the type says
Option<T>Some(T), Nonea value may be absent
Result<T, E>Ok(T), Err(E)an operation may fail, with a reason
OrderingLess, Equal, Greaterthe outcome of a comparison
ControlFlow<B, C>Continue(C), Break(B)whether a loop should keep going
Cow<'a, B>Borrowed(&'a B), Owned(B::Owned)data that is sometimes owned
IpAddrV4(Ipv4Addr), V6(Ipv6Addr)one variant per concrete struct

IpAddr is the pattern worth copying. Neither variant spells out its fields; each one holds a struct that stands alone, has its own methods and its own derives, and can be passed to a function that does not care about the enum.

When a payload has outgrown the variant

A variant with four or five fields is a struct wearing a disguise. Promote it:

// Before: the oven setting's data is trapped inside the variant.
enum Setting {
    Off,
    Bake { celsius: u16, fan: bool, rack: u8, preheat: bool },
}

// After: the payload is a type, so it can have methods and be passed alone.
#[derive(Debug, Clone, Copy)]
struct Bake {
    celsius: u16,
    fan: bool,
    rack: u8,
    preheat: bool,
}

enum Setting {
    Off,
    Bake(Bake),
}

Nothing is lost at the match site -- Setting::Bake(b) => preheat(&b) is shorter than destructuring four fields -- and a great deal is gained everywhere else: fn preheat(b: &Bake) becomes writable, Bake can derive Copy on its own terms, and a second variant can reuse it.

A payload of structs, in one program

#[derive(Debug, Clone)]
struct Address {
    city: String,
    postcode: String,
}

impl Address {
    fn short(&self) -> String {
        format!("{} {}", self.city, self.postcode)
    }
}

#[derive(Debug, Clone)]
struct Customer {
    name: String,
    address: Option<Address>,
}

#[derive(Debug)]
enum Response {
    Empty,
    One(Customer),
    Many(Vec<Customer>),
    Error { code: u16, message: String },
}

impl Response {
    fn summary(&self) -> String {
        match self {
            Response::Empty => String::from("no results"),
            Response::One(c) => format!("one result: {}", c.name),
            Response::Many(cs) => format!("{} results", cs.len()),
            Response::Error { code, message } => format!("error {code}: {message}"),
        }
    }

    fn count(&self) -> usize {
        match self {
            Response::One(_) => 1,
            Response::Many(cs) => cs.len(),
            _ => 0,
        }
    }

    // One accessor serves the single and the many case, so every method
    // built on top of it stops caring which variant arrived.
    fn customers(&self) -> &[Customer] {
        match self {
            Response::One(c) => std::slice::from_ref(c),
            Response::Many(cs) => cs,
            _ => &[],
        }
    }

    fn places(&self) -> Vec<String> {
        self.customers()
            .iter()
            .filter_map(|c| c.address.as_ref())
            .map(Address::short)
            .collect()
    }
}
fn main() {
    let ada = Customer {
        name: String::from("ada"),
        address: Some(Address {
            city: String::from("London"),
            postcode: String::from("N1 9GU"),
        }),
    };
    let linus = Customer {
        name: String::from("linus"),
        address: None,
    };
    let grace = Customer {
        name: String::from("grace"),
        address: Some(Address {
            city: String::from("New York"),
            postcode: String::from("10001"),
        }),
    };

    let responses = [
        Response::Empty,
        Response::One(ada.clone()),
        Response::Many(vec![ada, linus, grace]),
        Response::Error {
            code: 503,
            message: String::from("upstream unavailable"),
        },
    ];

    for r in &responses {
        println!("{:<32} count {}", r.summary(), r.count());
        println!("   places {:?}", r.places());
    }
}

Output:

no results                       count 0
   places []
one result: ada                  count 1
   places ["London N1 9GU"]
3 results                        count 3
   places ["London N1 9GU", "New York 10001"]
error 503: upstream unavailable  count 0
   places []

The customers method is the load-bearing line. std::slice::from_ref turns a &Customer into a one-element &[Customer] without allocating, the Many arm coerces &Vec<Customer> to &[Customer] by deref coercion, and the catch-all returns an empty slice -- so places and anything else built on top iterate uniformly and never re-match the enum. Note also the last row of the output: error 503: upstream unavailable is thirty-one characters, so the {:<32} field pads it by a single space and count still lands in the same column as the other rows. Two more characters in that message and the column would drift, which is the usual argument for computing a width rather than guessing one.


Real World Example: A Tiny JSON Value

Every JSON library in every language models the same six-way choice, and in Rust that choice is an enum. Two of the six variants are recursive, and neither one needs a Box -- Vec has already supplied the indirection.

#[derive(Debug, Clone, PartialEq)]
enum Json {
    Null,
    Bool(bool),
    Number(f64),
    Text(String),
    List(Vec<Json>),
    Object(Vec<(String, Json)>),
}

impl Json {
    fn type_name(&self) -> &'static str {
        match self {
            Json::Null => "null",
            Json::Bool(_) => "bool",
            Json::Number(_) => "number",
            Json::Text(_) => "string",
            Json::List(_) => "list",
            Json::Object(_) => "object",
        }
    }

    fn nodes(&self) -> usize {
        1 + match self {
            Json::List(items) => items.iter().map(Json::nodes).sum(),
            Json::Object(pairs) => pairs.iter().map(|(_, v)| v.nodes()).sum(),
            _ => 0,
        }
    }

    fn depth(&self) -> usize {
        match self {
            Json::List(items) => 1 + items.iter().map(Json::depth).max().unwrap_or(0),
            Json::Object(pairs) => 1 + pairs.iter().map(|(_, v)| v.depth()).max().unwrap_or(0),
            _ => 1,
        }
    }

    // Navigation returns a borrow, never a panic: a missing key and a wrong
    // variant both come back as None.
    fn get(&self, key: &str) -> Option<&Json> {
        match self {
            Json::Object(pairs) => pairs
                .iter()
                .find(|(k, _)| k.as_str() == key)
                .map(|(_, v)| v),
            _ => None,
        }
    }

    fn at(&self, index: usize) -> Option<&Json> {
        match self {
            Json::List(items) => items.get(index),
            _ => None,
        }
    }

    fn render(&self) -> String {
        match self {
            Json::Null => String::from("null"),
            Json::Bool(b) => b.to_string(),
            Json::Number(n) => n.to_string(),
            Json::Text(s) => format!("{s:?}"),
            Json::List(items) => {
                let inner: Vec<String> = items.iter().map(Json::render).collect();
                format!("[{}]", inner.join(","))
            }
            Json::Object(pairs) => {
                let inner: Vec<String> = pairs
                    .iter()
                    .map(|(k, v)| format!("{k:?}:{}", v.render()))
                    .collect();
                format!("{{{}}}", inner.join(","))
            }
        }
    }
}
fn main() {
    let doc = Json::Object(vec![
        (String::from("name"), Json::Text(String::from("ada"))),
        (String::from("active"), Json::Bool(true)),
        (String::from("score"), Json::Number(99.5)),
        (
            String::from("tags"),
            Json::List(vec![
                Json::Text(String::from("rust")),
                Json::Text(String::from("systems")),
            ]),
        ),
        (
            String::from("address"),
            Json::Object(vec![
                (String::from("city"), Json::Text(String::from("London"))),
                (String::from("zip"), Json::Null),
            ]),
        ),
    ]);

    println!("type   = {}", doc.type_name());
    println!("nodes  = {}", doc.nodes());
    println!("depth  = {}", doc.depth());
    println!("render = {}", doc.render());
    println!();

    println!("name        = {:?}", doc.get("name"));
    println!("tags[1]     = {:?}", doc.get("tags").and_then(|t| t.at(1)));
    println!("tags[9]     = {:?}", doc.get("tags").and_then(|t| t.at(9)));
    println!("address.zip = {:?}", doc.get("address").and_then(|a| a.get("zip")));
    println!("missing     = {:?}", doc.get("missing"));
}

Output:

type   = object
nodes  = 10
depth  = 3
render = {"name":"ada","active":true,"score":99.5,"tags":["rust","systems"],"address":{"city":"London","zip":null}}

name        = Some(Text("ada"))
tags[1]     = Some(Text("systems"))
tags[9]     = None
address.zip = Some(Null)
missing     = None

The recursion is the whole design, and the choice of container is what keeps it cheap. List(Vec<Json>) compiles with no Box because a Vec is already a fixed-size handle to a heap buffer -- twenty-four bytes of pointer, length and capacity, no matter how many elements sit behind it. Only a variant that would hold a Json directly needs boxing, and this type has none. Object(Vec<(String, Json)>) preserves key order, which a HashMap would not, and for the handful of keys a typical object carries a linear find beats hashing anyway.

Every method is one match with one recursive call inside it, and nodes and depth fit in four lines each because the type already describes its own shape. There is no case the compiler let me forget: adding a seventh variant tomorrow breaks all five methods at compile time, which is exactly the reminder you want. Note that nodes counts an object's keys as free -- ten nodes for a document with five keys, two tags and a nested object -- because a key is a String in a tuple, not a Json of its own.

Navigation is where the payload design pays off in ordinary code. get and at both return Option<&Json>, so and_then chains walk arbitrarily deep without a single unwrap and without a panic anywhere. doc.get("tags").and_then(|t| t.at(9)) returns None, and so would doc.get("name").and_then(|t| t.at(9)) -- one because the index is out of range, the other because a string is not a list -- and the calling code very rarely wants to tell those apart. Returning borrows rather than clones means the chain costs nothing but pointer arithmetic.

Two honest limits in render. f64::to_string prints 99.5 correctly but would print 1 for 1.0, which is valid JSON yet loses the integer-versus-float distinction, and that is precisely why real libraries carry separate i64 and f64 number variants instead of one f64. And format!("{s:?}") is borrowing Debug's quoting rules to do JSON string escaping: right for plain ASCII, wrong in general, since Debug and JSON disagree about how to escape several characters. A production type would spell out its own escaping and would almost certainly hold Box<str> keys to shave the capacity field off every one of them.


Common Mistakes

  1. Writing the recursive variant without indirection. Add(Expr, Expr) is error[E0072]: recursive type has infinite size, and no amount of rearranging the variants fixes it. The compiler needs a finite largest variant; a pointer is the only thing that gives it one.
  1. Boxing a container that already indirects. List(Box<Vec<Json>>) and List(Vec<Box<Json>>) both compile, and both are worse than List(Vec<Json>). The first adds an allocation to reach a handle that was already eight bytes away; the second adds one allocation per element.
  1. Boxing every variant instead of the oversized one. If Big::B([u8; 256]) is what makes the enum large, box that one field. Boxing A(u8) as well costs an allocation on the common path and shrinks nothing, because the size of an enum is set by its largest variant alone.
  1. Forgetting that construction needs Box::new even though matching does not. Rust inserts no indirection for you at the constructor, so every child is Box::new(...). In a pattern, though, Expr::Neg(inner) binds &Box<Expr> and deref coercion quietly hands it to anything expecting &Expr -- the asymmetry surprises people in both directions.
  1. Deriving Copy on an enum with an owning payload. #[derive(Copy)] on a variant holding a String, Vec or Box fails with error[E0204], because Copy demands that every field be duplicable by a plain bit-copy. Clone is the trait you wanted, and on a deep tree it is O(n) -- not the free copy Copy implies.
  1. Long unnamed tuple payloads. Add(Box<Expr>, Box<Expr>, bool, u8) forces every reader to remember what .2 and .3 meant. Past two fields, switch to a struct variant with named fields, or promote the payload to its own struct.
  1. Cloning a whole tree to read one leaf. Cloning doc before calling get deep-copies every string and every vector in the document in order to hand back a borrow of one of them -- and if the clone is a temporary, the borrow checker rejects the expression anyway. Accessors that return Option<&T> exist so that reading costs nothing at all.
  1. Building a pyramid of nested matches to reach nested data. Four levels of match ... { Some(x) => match ... } collapses into one and_then chain. The nesting is not more explicit, it is just taller, and it makes the early-None cases easy to get wrong.
  1. Assuming a generic enum's parameters are per-variant. Either<L, R> carries both parameters on every value even though Left never touches R. Either<String, u8> and Either<u8, String> are different types, and a function taking the first will not accept the second.

Best Practices

  • Reach for Box only when the recursion demands it, and confirm the effect with std::mem::size_of rather than assuming -- the number is often not what you guessed.
  • Let Vec<T> be the indirection when a variant has a variable number of children. One allocation for all of them beats one each, and the code reads better.
  • Promote a payload to its own struct as soon as it has more than two fields, or as soon as a function wants to take it alone. IpAddr::V4(Ipv4Addr) is the model.
  • Use named fields in struct variants whenever position alone does not make the meaning obvious. Error { code, message } survives a reordering; Error(u16, String) does not.
  • Return Option<&T> from accessors on a nested type and let callers chain with and_then. Nothing panics, nothing allocates, and the chain reads in the same order as the path it walks.
  • Put the recursion inside the method rather than in the caller. A nodes() that recurses is four lines; every caller writing its own tree walk is four lines each, and one of them will get depth wrong.
  • Model the distinctions the domain actually makes. If integers and floats mean different things downstream, that is two variants, not one f64 and a comment.
  • Derive sparingly on a recursive type. PartialEq and Clone are O(n) there, and Hash on a tree with an f64 in it will not compile at all -- add each derive when a call site needs it.

Practice Exercises

  1. Finish the calculator. Add Sub(Box<Expr>, Box<Expr>) and Div(Box<Expr>, Box<Expr>) to Expr, and change eval to return Option<f64> so that dividing by zero yields None instead of inf. Use the ? operator inside eval rather than nested matches, then evaluate three trees: one ordinary, one that divides by a subtraction which comes out to exactly zero, and one that nests the failing division three levels down. Confirm that the None propagates all the way out.
  1. A file-system tree. Define enum Node { File { name: String, bytes: u64 }, Dir { name: String, children: Vec<Node> } } and implement total_bytes(&self) -> u64, count_files(&self) -> usize and deepest_path(&self) -> String that joins names with / along the longest branch. Build a tree three levels deep with at least two directories at the second level, print all three results, and write a sentence explaining why children: Vec<Node> compiles while children: Node would not.
  1. Either, by hand. Define enum Either<L, R> { Left(L), Right(R) } with fn left(self) -> Option<L>, fn right(self) -> Option<R> and fn swap(self) -> Either<R, L>. Build a Vec<Either<String, u8>> holding a mix of both variants, then print how many of each it contains and the result of swapping every element. Finish with one sentence on why the swapped vector has a different type from the original.
  1. Measure the indirection. Define enum Small { A(u8), B(u16) } and enum Big { A(u8), B([u8; 256]) }, then print size_of for both. Change Big::B to hold Box<[u8; 256]> and print again. Write down all three numbers, then say which of the two Big layouts you would choose for a channel that carries ninety per cent A values, and which you would choose if the receiver reads the 256 bytes every time.