Enums: Algebraic Data Types

Enums: Algebraic Data Types in Rust: An oven's control panel carries two different kinds of control.

The Analogy: The Oven's Mode Switch

An oven's control panel carries two different kinds of control. There is a row of readouts -- temperature, time elapsed, fan speed -- and every one of them holds a value at the same time. That is a struct. Then there is the mode switch: a single rotary dial that clicks between Off, Bake, Grill and Defrost. The dial is in exactly one position. Never two. Never none.

Behind the panel, those positions are not interchangeable. "Off" needs no wiring at all. "Bake" needs a target temperature. "Grill" needs a power level from one to five. "Defrost" needs a weight, because the oven computes the time from it. Four positions, four different sets of terminals, one switch.

That is what makes the switch trustworthy rather than merely tidy. You cannot read the grill power while the dial sits on Defrost, because there is no terminal to read it from. In a design where all four settings were separate dials, you could read it, and you would get whatever was left over from the last cook. The switch does not only record which mode is active -- it makes the irrelevant settings physically unreachable.

Rust's enum is that dial. Each variant is a position, each variant may carry data of its own shape, and a value of the type is always exactly one variant. Getting at a variant's data requires first establishing which variant you are holding, and the compiler will not let you skip that step. So the entire class of bug where you read a field that does not apply is not caught late in testing; it cannot be written down.


Syntax or Core Structure

Variants come in the same three shapes struct fields do: nothing, a tuple, or named fields. A single enum can mix all three.

// A C-style enum: the variants are just names.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Mode {
    Off,
    Bake,
    Grill,
    Defrost,
}

// Variants carrying their own data. This is the part that matters.
#[derive(Debug)]
enum Setting {
    Off,
    Bake { celsius: u16, fan: bool },
    Grill(u8),
    Defrost(f32),
}

fn main() {
    let cycle = [Mode::Off, Mode::Bake, Mode::Grill, Mode::Defrost];
    println!("cycle = {cycle:?}");
    println!("second is Bake: {}", cycle[1] == Mode::Bake);

    // Four different shapes of data; still one type, so they fit in one array.
    let settings = [
        Setting::Off,
        Setting::Bake { celsius: 180, fan: true },
        Setting::Grill(3),
        Setting::Defrost(1.5),
    ];

    for s in &settings {
        println!("{:?}  ->  {}", s, describe(s));
    }
}

fn describe(s: &Setting) -> String {
    match s {
        Setting::Off => String::from("nothing running"),
        Setting::Bake { celsius, fan } => {
            format!("bake at {celsius}C, fan {}", if *fan { "on" } else { "off" })
        }
        Setting::Grill(level) => format!("grill at level {level} of 5"),
        Setting::Defrost(kg) => format!("defrost {kg} kg"),
    }
}

Output:

cycle = [Off, Bake, Grill, Defrost]
second is Bake: true
Off  ->  nothing running
Bake { celsius: 180, fan: true }  ->  bake at 180C, fan on
Grill(3)  ->  grill at level 3 of 5
Defrost(1.5)  ->  defrost 1.5 kg

Two things to notice. All four settings sit in one array despite holding different data, because they are all Setting -- the differences are inside the value, not in its type. And describe never asks "does this one have a celsius?"; the match establishes the variant and the fields come with it, already the right ones.

Try to skip that step and the compiler stops you:

fn main() {
    let s = Setting::Grill(3);
    println!("{}", s.0);
}

Output:

error[E0609]: no field `0` on type `Setting`
 --> src/main.rs:3:22
  |
3 |     println!("{}", s.0);
  |                      ^

Setting::Grill has a field 0. Setting does not, and s is a Setting. That distinction is the whole mechanism: the data belongs to the variant, and you reach it by proving which variant you have.


Technical Depth: Sums, Tags, and Niches

Products and sums

A struct is an and: a Parcel has a weight and a value and a country. An enum is an or: a Setting is Off or Bake or Grill or Defrost. Together they are what the literature calls algebraic data types, and the algebra is literal -- a struct's possible values multiply, an enum's add up. A struct of two bool fields has four possible values; an enum of two fieldless variants has two.

Questionstructenum
how many fields hold dataall of themonly the current variant's
adding oneevery constructor must supply itevery exhaustive match must handle it
sizefields, reordered and paddedlargest variant, plus a tag
what the compiler catchesyou cannot forget to set a fieldyou cannot forget to handle a case

Those last two rows are the trade. A struct pushes the cost of change onto whoever constructs a value; an enum pushes it onto whoever reads one. Both are checked, which is the point.

An enum is a tag plus the largest payload

use std::mem::size_of;

#[allow(dead_code)]
enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let rows = [
        ("Direction", size_of::<Direction>()),
        ("u64", size_of::<u64>()),
        ("Option<u64>", size_of::<Option<u64>>()),
        ("Option<&u64>", size_of::<Option<&u64>>()),
        ("String", size_of::<String>()),
        ("Option<String>", size_of::<Option<String>>()),
        ("Option<bool>", size_of::<Option<bool>>()),
    ];
    for (name, size) in rows {
        println!("{name:<14} = {size}");
    }
}

Output (on a 64-bit target):

Direction      = 1
u64            = 8
Option<u64>    = 16
Option<&u64>   = 8
String         = 24
Option<String> = 24
Option<bool>   = 1

Four variants with no data need one byte, because the tag is all there is. Option<u64> needs sixteen rather than nine: the tag takes a byte and then alignment rounds the whole thing up to a multiple of eight.

The three interesting rows are the ones where the tag costs nothing. A reference can never be null, so Option<&u64> spends the all-zero bit pattern on None and stays at eight bytes. String holds a non-null pointer, so Option<String> uses the same trick and stays at twenty-four. bool occupies a byte but only uses the values 0 and 1, so Option<bool> spends 2 on None and stays at one byte. This is called niche optimisation, and it means wrapping a pointer-like or restricted type in Option is usually free -- which is why Rust can offer Option instead of null without an efficiency argument to answer.

Explicit discriminants, and the one-way street

A fieldless enum can name its own tag values and be cast to an integer.

#[derive(Debug, Clone, Copy)]
enum Status {
    Ok = 200,
    NotFound = 404,
    Teapot = 418,
    ServerError = 500,
}

fn main() {
    for s in [Status::Ok, Status::NotFound, Status::Teapot, Status::ServerError] {
        println!("{s:?} = {}", s as u16);
    }
}

Output:

Ok = 200
NotFound = 404
Teapot = 418
ServerError = 500

Three constraints go with this. Casting with as only works when no variant carries data -- there is nothing sensible to cast otherwise, and the compiler rejects it. Without explicit values the discriminants start at zero and count up. And the reverse direction does not exist: there is no built-in u16 to Status cast, because most u16 values are not statuses. You write that yourself as a match returning Option<Status>, or implement TryFrom, and either way the impossible values have to be dealt with explicitly.

Enums get impl blocks too

Nothing about methods is struct-specific. An enum's methods usually open with a match, which is exactly what you want: the behaviour for each case sits next to the case.

#[derive(Debug, Clone, Copy, PartialEq)]
enum Shape {
    Circle { r: f64 },
    Rect { w: f64, h: f64 },
    Triangle { b: f64, h: f64 },
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle { r } => std::f64::consts::PI * r * r,
            Shape::Rect { w, h } => w * h,
            Shape::Triangle { b, h } => 0.5 * b * h,
        }
    }

    // The .. says "I do not care about the payload, only the shape".
    fn name(&self) -> &'static str {
        match self {
            Shape::Circle { .. } => "circle",
            Shape::Rect { .. } => "rect",
            Shape::Triangle { .. } => "triangle",
        }
    }

    fn scaled(self, k: f64) -> Self {
        match self {
            Shape::Circle { r } => Shape::Circle { r: r * k },
            Shape::Rect { w, h } => Shape::Rect { w: w * k, h: h * k },
            Shape::Triangle { b, h } => Shape::Triangle { b: b * k, h: h * k },
        }
    }
}

fn main() {
    let shapes = [
        Shape::Circle { r: 1.0 },
        Shape::Rect { w: 3.0, h: 4.0 },
        Shape::Triangle { b: 6.0, h: 2.0 },
    ];

    for s in shapes {
        println!(
            "{:<8} area {:>6.2}  doubled {:>7.2}",
            s.name(),
            s.area(),
            s.scaled(2.0).area()
        );
    }
}

Output:

circle   area   3.14  doubled   12.57
rect     area  12.00  doubled   48.00
triangle area   6.00  doubled   24.00

area and name take &self and read; scaled takes self and returns a new value, which is why s.scaled(2.0).area() composes. Note that Shape is Copy, so s survives the scaled call -- were one of the fields a String, scaled would consume s and the println! arguments would have to be reordered.

Variants are not types

This is the one piece of enum syntax that surprises everybody:

error[E0573]: expected type, found variant `Shape::Circle`

Shape::Circle is a constructor and a pattern, not a type. You cannot write fn area_of(c: Shape::Circle), because there is no such type to write down -- there is only Shape. If you genuinely need a function that accepts circles and nothing else, make Circle its own struct and have the variant hold it: Circle(Circle). That is a common and idiomatic move once a variant's payload grows beyond two or three fields.


Real World Example: A Job State Machine With No Invalid States

Every background-job system needs to answer "what is this job doing". The tempting shape is a struct with a status string and a pile of optional fields. Here is what that looks like:

// The version to avoid.
struct Job {
    state: String,
    position: Option<u32>,
    worker: Option<String>,
    percent: Option<u8>,
    output: Option<String>,
    seconds: Option<u32>,
    error: Option<String>,
    retryable: Option<bool>,
}

Seven optional fields is one hundred and twenty-eight combinations of present and absent, of which five are meaningful. Nothing stops a job from being "queued" with an error set, or "running" with no worker. Every reader has to unwrap fields it believes must be there, and every one of those unwraps is a possible panic that the type system was never asked about. Here is the same information as an enum:

#[derive(Debug)]
enum Job {
    Queued { position: u32 },
    Running { worker: String, percent: u8 },
    Succeeded { output: String, seconds: u32 },
    Failed { error: String, retryable: bool },
    Cancelled,
}

impl Job {
    fn label(&self) -> String {
        match self {
            Job::Queued { position } => format!("queued, {position} ahead"),
            Job::Running { worker, percent } => format!("running on {worker}, {percent}%"),
            Job::Succeeded { output, seconds } => {
                format!("succeeded in {seconds}s ({output})")
            }
            Job::Failed { error, retryable } => {
                format!("failed: {error} (retryable: {retryable})")
            }
            Job::Cancelled => String::from("cancelled"),
        }
    }

    fn is_terminal(&self) -> bool {
        matches!(
            self,
            Job::Succeeded { .. } | Job::Failed { .. } | Job::Cancelled
        )
    }

    fn should_retry(&self) -> bool {
        matches!(self, Job::Failed { retryable: true, .. })
    }

    // Taking self by value means the old state is consumed, not copied.
    fn advance(self) -> Job {
        match self {
            Job::Queued { position: 0 } => Job::Running {
                worker: String::from("worker-1"),
                percent: 0,
            },
            Job::Queued { position } => Job::Queued {
                position: position - 1,
            },
            Job::Running { worker, percent } if percent >= 75 => Job::Succeeded {
                output: format!("built by {worker}"),
                seconds: 12, // a real runner would read a clock here
            },
            Job::Running { worker, percent } => Job::Running {
                worker,
                percent: percent + 25,
            },
            terminal => terminal,
        }
    }
}

fn main() {
    let mut job = Job::Queued { position: 2 };
    let mut step = 0;

    // The step cap is a safety net, not part of the logic.
    while !job.is_terminal() && step < 20 {
        println!("{step:>2}  {}", job.label());
        job = job.advance();
        step += 1;
    }
    println!("{step:>2}  {}", job.label());

    println!();
    println!("terminal: {}", job.is_terminal());
    println!("retry:    {}", job.should_retry());
    println!("{job:?}");

    println!();
    for j in [
        Job::Failed {
            error: String::from("timeout"),
            retryable: true,
        },
        Job::Failed {
            error: String::from("bad input"),
            retryable: false,
        },
        Job::Cancelled,
    ] {
        println!(
            "{:<38} terminal {:<5} retry {}",
            j.label(),
            j.is_terminal(),
            j.should_retry()
        );
    }
}

Output:

 0  queued, 2 ahead
 1  queued, 1 ahead
 2  queued, 0 ahead
 3  running on worker-1, 0%
 4  running on worker-1, 25%
 5  running on worker-1, 50%
 6  running on worker-1, 75%
 7  succeeded in 12s (built by worker-1)

terminal: true
retry:    false
Succeeded { output: "built by worker-1", seconds: 12 }

failed: timeout (retryable: true)      terminal true  retry true
failed: bad input (retryable: false)   terminal true  retry false
cancelled                              terminal true  retry false

The invalid combinations did not become guarded against -- they became unwritable. Job::Running has no error field to set, Job::Cancelled has no fields at all, and there is no state in which percent is absent while the job runs. Every unwrap from the struct version is gone, because there is no longer anything optional: if you are looking at Job::Failed, you have an error and a retryable, both of them, always.

advance taking self by value is doing real work. The old state is consumed, so no caller can keep a handle on a stale state and act on it afterwards -- the transition is the only way forward and it is one-way. That, plus exhaustive matching, means adding a Paused variant turns into a list of compile errors naming every place that has to make a decision about it.

matches! covers the questions that are about shape rather than content. is_terminal genuinely does not care what the payloads are, and Job::Succeeded { .. } says so in the pattern instead of binding three variables it will not use. should_retry goes one step further and matches the literal true inside the pattern, filtering on shape and data in a single expression -- which is shorter and harder to get wrong than pulling retryable out and testing it.

One line in that program deserves suspicion, and it is terminal => terminal. It is convenient, and it is precisely the construct that converts "someone added a variant" from a compile error into silent wrong behaviour: add Paused and it falls into the catch-all and simply never advances, with nothing anywhere to warn you. Writing the three terminal variants out explicitly costs two extra lines and buys back the exhaustiveness guarantee that was the reason for choosing an enum in the first place. In a state machine that is a trade worth making every time.


Common Mistakes

  1. Reaching for a variant's data without matching. s.0 or s.celsius on a Setting gives error[E0609]: no field ... on type Setting. The field belongs to the variant, and you get at it by establishing the variant first.
  1. Casting a data-carrying enum with as. Setting::Grill(3) as u16 does not compile. Integer casts are only available on enums where no variant carries data, because otherwise there is nothing coherent to produce.
  1. Expecting a cast back from an integer. There is no 404 as Status. Most u16 values are not statuses, so you write the reverse mapping yourself -- a match returning Option<Status>, or a TryFrom implementation -- and handle the values that are not.
  1. Reaching for _ => out of habit. A catch-all arm makes the match exhaustive forever, so the next variant someone adds compiles silently and behaves wrongly. Use it when the remaining cases genuinely share behaviour, not to save typing.
  1. Letting one fat variant inflate every value. An enum is as large as its biggest variant, so a single Variant([u8; 512]) makes every value of that type 520-odd bytes, including the empty ones. Box the large payload and the enum shrinks back to pointer size.
  1. Modelling an "or" as a struct full of Options. Seven optional fields is a hundred and twenty-eight combinations to reason about instead of five. If the fields are only meaningful in particular groupings, the groupings are variants.
  1. Treating a variant as a type. fn f(c: Shape::Circle) gives error[E0573]: expected type, found variant. Variants are constructors and patterns. When a variant's payload wants its own type, define a struct and let the variant hold it.
  1. Assuming derived ordering follows the variant names. Derived PartialOrd and Ord on an enum compare by declaration order, so Low, Medium, High sorts sensibly and High, Low, Medium does not. Reordering the variants silently reorders every sort.
  1. Repeating the type's name in every variant. enum Shape { ShapeCircle, ShapeRect } reads as Shape::ShapeCircle at every use site. The path already carries the type name; clippy's enum_variant_names lint will say so.

Best Practices

  • Model "exactly one of these" as an enum, every time. A status string beside a set of nullable fields is the same information with the guarantees removed.
  • Put each piece of data on the variant that needs it and on no other. A field that is meaningful in three states out of five is a hint that the shape is not quite right yet.
  • Prefer exhaustive matches over _. The compile errors you get when adding a variant are the feature you paid for; a catch-all arm silently declines them.
  • Reach for matches! when the answer is a bool. matches!(self, Job::Cancelled) is clearer than a five-arm match that returns true once.
  • Box a variant that is much larger than its siblings, and check with size_of rather than guessing. The indirection costs one pointer hop on the rare path and saves the size on every value.
  • Give the enum an impl block and keep the per-variant behaviour there. A match in a method is the case analysis stated once, instead of the same match copied into four call sites.
  • Take self by value for a transition that replaces one state with another. Consuming the old value is what stops anyone from acting on it afterwards.
  • Mark a public enum #[non_exhaustive] if you expect to add variants. Without it, adding one is a breaking change for everybody who wrote an exhaustive match against it.

Practice Exercises

  1. Model a JSON value. Define enum Json { Null, Bool(bool), Number(f64), Text(String), List(Vec<Json>), Object(Vec<(String, Json)>) }. Add fn type_name(&self) -> &'static str and fn count_nodes(&self) -> usize that counts the value itself plus everything nested inside it. Build a value with a list inside an object, print both results, and explain why Vec is what makes the recursive definition legal.
  1. Retire the Options. Take the struct with state: String and seven Option fields from this lesson and finish the enum conversion yourself, then write down two specific invalid values the struct permits and the enum cannot express. Add a fn from_row(state: &str, position: Option<u32>) -> Option<Job> that validates a database row into the enum, returning None for a row that does not make sense.
  1. Discriminants both ways. Define a fieldless Signal enum with explicit discriminants matching Unix signal numbers, cast a value out with as u8, then write fn from_code(code: u8) -> Option<Signal> for the return trip. Explain in one sentence why the outbound direction can be a cast and the inbound one cannot.
  1. Measure a fat variant. Define enum Packet { Ping, Pong, Payload([u8; 512]) } and print size_of::<Packet>(). Change the third variant to Payload(Box<[u8; 512]>) and print it again. Note both numbers, then say which version you would choose for a queue of mostly-Ping packets and which for a queue of mostly-Payload ones.