Skip to content
RustLearn

Module 07 — Enums & Pattern Matching

Goal

Make illegal states unrepresentable. Enums carry data, match is exhaustive, and the compiler refuses to let you forget a case.

Start here — what this module is really about

Module 06 gave you a way to say and: a rectangle has a width and a height. This module gives you a way to say or, and it turns out to be the more powerful of the two.

An enum lists every form a value is allowed to take:

rust
enum Status {
    Loading,
    Ready,
    Failed,
}

If you have met enums in C or Java, note the crucial difference: in Rust each variant can carry its own data, of its own shape.

rust
enum Message {
    Quit,                        // nothing
    Move { x: i32, y: i32 },     // named fields, like a struct
    Write(String),               // one value
}

That is why Rust enums are sometimes called sum types or tagged unions: the value is exactly one of these forms, and it carries precisely the data that form needs. Not "a status code plus an optional error message plus an optional payload, and you work out which combination is legal" — one form, one shape, no illegal combinations expressible.

The tool for taking them apart is match, and its defining feature is that it is exhaustive: the compiler refuses to compile a match that does not handle every variant. This sounds like bureaucracy and is actually the feature. When you add a new variant six months from now, the compiler hands you a list of every place in the codebase that must now make a decision. No silent fall-through, no default branch quietly doing the wrong thing.

The one sentence to remember: enums let you make illegal states impossible to construct, and match makes it impossible to forget a case.

Learning objectives

  • Define enums that carry data, and understand them as sum types
  • Use match exhaustively, with guards, bindings, ranges, and _
  • Destructure structs, tuples, references, and nested values
  • Use if let, let else, while let, and matches!
  • Model a domain so that illegal states are unrepresentable

7.1 Enums are sum types

A struct says "A and B and C". An enum says "A or B or C". That's the whole difference, and it's why enums are the more powerful tool for modelling.

rust
#[derive(Debug)]
enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));

Each variant can carry different data — or none:

rust
#[derive(Debug)]
enum Message {
    Quit,                          // no data
    Move { x: i32, y: i32 },       // named fields, like a struct
    Write(String),                 // one value, like a tuple struct
    ChangeColor(i32, i32, i32),    // several values
}

The size of an enum is the size of its largest variant plus a discriminant tag. Rust also performs niche optimization: Option<&T> is the same size as &T, because the null pointer value is used to represent None. That's why "nullable references" cost nothing.

Enums get impl blocks like structs:

rust
impl Message {
    fn call(&self) {
        match self {
            Message::Quit => println!("quit"),
            Message::Move { x, y } => println!("move to {x},{y}"),
            Message::Write(text) => println!("write {text}"),
            Message::ChangeColor(r, g, b) => println!("color #{r:02x}{g:02x}{b:02x}"),
        }
    }
}

TS ↔ Rust: Rust enums are discriminated unions (type Message = { kind: 'quit' } | { kind: 'move', x: number, y: number } | ...), but with exhaustiveness enforced by the compiler and no runtime tag string.


Analogy — the shape of a door

A struct is and: a rectangle has a width and a height. An enum is or: a traffic light is red or amber or green, never two at once. Modelling with or is how whole categories of bug stop being possible — there is simply no way to construct a light that is red and green, so there is no code to write handling that case.

7.2 match

rust
#[derive(Debug)]
enum Coin { Penny, Nickel, Dime, Quarter }

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

Properties that make match different from a switch:

  1. Exhaustive. Miss a variant and it's a compile error:
    error[E0004]: non-exhaustive patterns: `Coin::Quarter` not covered
    
    Add a variant to the enum a year later and the compiler shows you every match that now needs updating. This is the single best refactoring tool in the language.
  2. It's an expression. Every arm must produce the same type.
  3. It binds data. Patterns destructure as they match.
  4. First match wins, top to bottom.

Binding values

rust
enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
    Triangle(f64, f64, f64),
}

fn area(s: &Shape) -> f64 {
    match s {
        Shape::Circle(r) => std::f64::consts::PI * r * r,
        Shape::Rect { w, h } => w * h,
        Shape::Triangle(a, b, c) => {
            let s = (a + b + c) / 2.0;
            (s * (s - a) * (s - b) * (s - c)).sqrt()
        }
    }
}

Catch-all patterns

rust
let dice = 7;
match dice {
    3 => println!("gain a hat"),
    7 => println!("lose a hat"),
    other => println!("move {other} spaces"),   // binds the value
}

match dice {
    3 | 5 | 7 => println!("odd-ish"),           // or-patterns
    1..=6 => println!("normal roll"),           // inclusive range
    _ => println!("something else"),            // ignore the value
}

_ matches anything and binds nothing. other matches anything and binds it. Prefer _ when you truly don't care, so the reader knows.

Match guards

rust
let pair = (3, -3);
match pair {
    (x, y) if x + y == 0 => println!("sum to zero"),
    (x, _) if x % 2 == 0 => println!("first is even"),
    _ => println!("no match"),
}

Guards are checked after the pattern matches. Note the compiler does not consider guards when checking exhaustiveness — a guarded arm never counts as covering a case, so you'll still need a fallback.

@ bindings

rust
match age {
    n @ 0..=12 => println!("child, age {n}"),
    n @ 13..=19 => println!("teen, age {n}"),
    n => println!("adult, age {n}"),
}

@ lets you both test a pattern and keep the value.


Reading a match, piece by piece

rust
let description = match message {
    Message::Quit => String::from("quitting"),
    Message::Move { x, y } => format!("moving to {x}, {y}"),
    Message::Write(text) => format!("writing: {text}"),
};

What each part is doing:

  1. match message — the value being examined. It is moved or borrowed here like anything else, which matters: matching on a String-carrying variant by value moves it.
  2. Each line is an arm: a pattern, =>, then the value that arm produces.
  3. The patterns destructure. Message::Move { x, y } does not just recognise the variant — it pulls the two numbers out into local variables named x and y, ready to use on the right-hand side. Message::Write(text) does the same for the string.
  4. match is an expression, so the whole thing produces a value that is being assigned to description. Every arm must therefore produce the same type — a rule you met with if in module 03.
  5. The semicolon at the end belongs to the let statement, not the match.

Now delete one arm and try to compile:

text
error[E0004]: non-exhaustive patterns: `Message::Write(_)` not covered

The compiler names the exact variant you forgot. This is the safety net that makes large Rust refactors calm: change the enum, then fix every error the compiler lists, and you are done.

A note on _: the pattern _ => ... matches anything left over. It is genuinely useful, but reach for it sparingly on your own enums — using it means adding a variant later will not produce errors, and you have just given away the feature that makes this worth doing.

Analogy — the exhaustive checklist

A switch in most languages is a suggestion box: handle the cases you thought of, and the rest fall through into whatever happens next. match is a checklist an inspector will not sign until every box is ticked. That is unglamorous right up to the day you add a new variant and the compiler hands you the exact list of every place in the codebase that now needs a decision.

7.3 Destructuring everything

rust
struct Point { x: i32, y: i32 }

let p = Point { x: 0, y: 7 };

let Point { x, y } = p;                 // irrefutable pattern in a let
match p {
    Point { x: 0, y: 0 } => println!("origin"),
    Point { x: 0, y }    => println!("on the y axis at {y}"),
    Point { x, y: 0 }    => println!("on the x axis at {x}"),
    Point { x, y }       => println!("({x}, {y})"),
}

// nested
enum Msg { Move(Point), Quit }
match msg {
    Msg::Move(Point { x, y: 0 }) => println!("horizontal move to {x}"),
    Msg::Move(p) => println!("move to {},{}", p.x, p.y),
    Msg::Quit => println!("quit"),
}

// tuples and ignoring
let numbers = (2, 4, 8, 16, 32);
let (first, .., last) = numbers;        // `..` skips the middle
let (_, second, ..) = numbers;

Prefixing a binding with _ silences the unused-variable warning while still binding; a bare _ binds nothing at all (which matters for ownership — let _ = value; drops it immediately, let _x = value; keeps it alive to end of scope).

Matching references

rust
let v = vec![1, 2, 3];
for x in &v {
    match x {
        1 => println!("one"),        // match ergonomics: x is &i32, pattern is i32
        n => println!("{n}"),
    }
}

Since Rust 2021, match ergonomics auto-dereference for you, so you rarely write & in patterns. When you do need the old behaviour, ref and ref mut still exist.

7.4 Concise forms

if let

rust
let config: Option<u8> = Some(3);

// verbose
match config {
    Some(max) => println!("max is {max}"),
    None => {}
}

// concise
if let Some(max) = config {
    println!("max is {max}");
} else {
    println!("no max set");
}

Use if let when you care about exactly one pattern. Use match when you care about several — it keeps exhaustiveness checking on your side.

let else (Rust 1.65+)

rust
fn parse_port(s: &str) -> u16 {
    let Ok(port) = s.parse::<u16>() else {
        eprintln!("bad port, defaulting to 8080");
        return 8080;
    };
    port                      // `port` is in scope for the rest of the function
}

The else block must diverge (return, break, continue, or panic!). This flattens the deeply-nested "happy path" that if let chains produce.

while let

rust
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
    println!("{top}");        // 3 2 1
}

matches!

rust
let x = Some(4);
assert!(matches!(x, Some(n) if n > 3));
assert!(matches!('c', 'a'..='z'));

Returns a bool — perfect for filter predicates and assertions.

7.5 Modelling with enums

The payoff of sum types is making illegal states unrepresentable. Compare:

rust
// ❌ struct-based: 4 combinations, 2 of which are nonsense
struct Connection {
    is_connected: bool,
    session_id: Option<String>,
    error: Option<String>,
}

// ✅ enum-based: exactly the 3 real states
enum Connection {
    Disconnected,
    Connected { session_id: String },
    Failed { error: String, retry_after: u32 },
}

With the enum version there is no way to construct a "connected but no session id" value, and no match can forget to handle failure.

A state machine falls out naturally:

rust
impl Connection {
    fn tick(self) -> Connection {
        match self {
            Connection::Disconnected => Connection::Connected { session_id: "abc".into() },
            Connection::Failed { retry_after: 0, .. } => Connection::Disconnected,
            Connection::Failed { error, retry_after } =>
                Connection::Failed { error, retry_after: retry_after - 1 },
            other => other,
        }
    }
}

Taking self by value makes transitions explicit: the old state is consumed, so you can never use a stale state by accident.


Designing with enums — the move that removes bugs

Here is a shape almost everyone writes first, in any language:

rust
struct Connection {
    is_connected: bool,
    session_id: Option<String>,   // only meaningful when connected
    error: Option<String>,        // only meaningful when it failed
}

Ask what happens when is_connected is true and session_id is None. Nothing prevents it. That combination is meaningless, yet every function reading this struct must handle it — usually with a .unwrap() and a silent prayer.

Now the same thing as an enum:

rust
enum Connection {
    Disconnected,
    Connected { session_id: String },
    Failed { error: String },
}

The meaningless combination cannot be written. There is no session_id field to leave empty when disconnected, because that field only exists inside the Connected form. Every reader gets the data that is actually relevant, guaranteed to be there, and match makes sure they handle all three cases.

This is the single most valuable habit from this module, and it has a name: make illegal states unrepresentable. When you find yourself writing a bool next to an Option that is "only valid when the bool is true", you are describing an enum.

Analogy — make the illegal state unbuildable

A struct with is_logged_in: bool plus an Option<User> is a form on which somebody can tick 'logged in' and leave the name blank — so every reader of that form must handle a state that should never exist. An enum with LoggedOut and LoggedIn(User) is a form where the impossible combination has no box to tick at all. Prefer making a bad state unbuildable over checking for it forever.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
enumA type whose value is exactly one of several named forms.
variantOne of those forms.
sum typeThe formal name for an enum that carries data — "this OR that".
matchThe construct that examines a value and runs the arm matching its shape.
armOne pattern => result line of a match.
exhaustiveCovering every possible case. Rust requires this of match.
destructuringPulling the pieces out of a value inside a pattern.
match guardAn extra if condition on an arm: Some(x) if x > 5 =>.
binding @Capturing a value while also testing it: n @ 1..=5.
if letShorthand for a match where you only care about one pattern.
catch-all _A pattern that matches anything, used for "everything else".

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0004]: non-exhaustive patternsYour match does not cover every variant.Add the missing arm the message names. Prefer that to _ on your own enums.
error[E0308]: match arms have incompatible typesArms produce different types, so the match has no single type.Make every arm produce the same type.
error[E0382]: use of moved value after a matchAn arm bound a field by value, moving it out.Match on a reference (match &message) or bind with ref.
unreachable pattern warningAn earlier arm already covers this one.Arms are tried in order — move the specific case above the general one.
error[E0532]: expected tuple struct or tuple variantPattern shape does not match the variant's shape.Struct-like variants need Variant { field }, tuple-like need Variant(value).

Now make it stick: work through the drills for this module, then carry on to Module 08 — Option, Result & Error Handling.