Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 132 ยท Structs, Enums and Traits Basics

Modelling with Enums and Pattern Matching

Design with Rust enums and match - expression trees, command parsers, state machines, replacing class hierarchies, exhaustive matches as a refactoring net, non_exhaustive.

Enums showed the syntax. This lesson is about the craft: how experienced Rust programmers turn a problem into types so that wrong programs do not compile. The central trick is simple. Describe every case your program can be in as an enum variant carrying exactly the data of that case, and then write functions that match on it. The compiler checks that you handled every case, today and after every future change.

We will build an expression evaluator, a command parser, a small traffic-light state machine and a "shape hierarchy" without inheritance, then see why exhaustive matching is a refactoring safety net and what #[non_exhaustive] is for. You should be comfortable with match, Enums and Box and the Heap (recursive types need a Box).

Make illegal states unrepresentable

Suppose a network request is loading, succeeded with a body, or failed with an error code. A beginner's first design is a struct with flags:

Rust
struct Response {
    is_loading: bool,
    body: Option<String>,
    error_code: Option<u16>,
}

Which combinations are valid? is_loading == true and body.is_some()? Both body and error_code set? The struct allows 2 x 2 x 2 = 8 combinations, but only 3 make sense, and every function must defensively check the rest. With an enum, the three real states are the only possible values:

Rust Three states instead of eight flag combinations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This habit is called making illegal states unrepresentable. Notice the nested pattern Failure { code: 404 }: arms are checked top to bottom, so the special case goes before the general Failure { code }.

An expression evaluator

A classic use of enums is a tree of operations. An expression is a number, or an operation applied to two sub-expressions. The recursive part needs a Box, because a type cannot contain itself directly (it would have infinite size):

Rust A recursive Expr enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two functions, eval and show, each walk the same tree with one arm per variant. The ? operator (The ? Operator) passes errors up. Adding a Sub variant later makes both match expressions fail to compile until you add the arm, so you cannot forget show.

Pattern-based simplification

Because patterns can look inside a variant, you can write rewrite rules almost like algebra:

Rust Simplifying with nested patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The tuple pattern (Num(0), x) | (x, Num(0)) is an or-pattern; both alternatives bind the same name x. The final other => other arm passes Num and Var through unchanged.

Commands: parsing text into enums

Programs that accept input usually turn text into a command value first, then execute the command. The enum documents everything the program can do:

Rust A command parser and executor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The Input box holds a few commands; edit them and run again. Parsing and execution are separate steps: parse can be tested without touching stdin, and main only decides what each command does.

A state machine with transitions in one place

A state machine is an enum of states plus an enum of events and a single function next(state, event). All the rules live in one match on a tuple:

Rust Traffic light state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Arms are tried in order, so the first rule, (_, Event::Fault), handles faults in every state. The compiler checks that all 12 combinations of state and event are covered. When the states carry data, as in the order example from Enums, transitions that take self by value make it impossible to keep using a stale state.

Replacing a class hierarchy

In an object-oriented language you might write an abstract Shape class with Circle, Square subclasses and a virtual area() method. With an enum, the set of shapes is closed and known:

Rust An enum instead of inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare the trade-off:

Enum Trait objects
New operation (e.g. volume) add one method, touch no variants must edit every type
New variant (e.g. Triangle) every match must be updated (the compiler lists them) add one type, nothing else changes
Set of types closed, known in one place open, extensible by other crates
Memory stored inline, no allocation usually boxed, plus a vtable call

Enums are the better choice when you own all the variants. Choose trait objects when users of your library need to add their own types.

Which to pick for state and event pairs

Matching on a tuple (state, event) keeps every rule in one table-like place, which is easy to review and to test. If the machine grows large, or each state has very different data and behaviour, give each state its own method instead (the order example in Enums does this) so that a state's rules sit next to its data. Both styles get compiler-checked exhaustiveness.

Exhaustive matching as a safety net

Say you add Triangle { base: f64, height: f64 } to Shape. Every match self without a wildcard now fails to compile:

TEXT
error[E0004]: non-exhaustive patterns: `&Shape::Triangle { .. }` not covered

You are led to every place that needs a decision, including ones you forgot existed. That only works if you avoid wildcard arms (_ => ...) for enums you own and expect to grow. A _ arm quietly absorbs new variants into whatever the default was. Use _ when the remaining cases truly share one behavior ("everything else is an error"); list variants explicitly when each deserves a conscious decision.

If you want to find every match that would be affected before writing the arms, temporarily add the variant and run cargo check (or just press Run here). The error list is your to-do list.

#[non_exhaustive]: enums that will grow

A library has the opposite problem: adding a variant is a breaking change for every user whose match listed all variants. The attribute #[non_exhaustive] on an enum tells other crates that more variants may appear, so they must always include a wildcard arm:

Rust
// in a library crate
#[non_exhaustive]
pub enum ErrorKind {
    NotFound,
    PermissionDenied,
    TimedOut,
}
Rust
// in a crate that depends on the library
match err.kind() {
    ErrorKind::NotFound => { /* ... */ }
    ErrorKind::PermissionDenied => { /* ... */ }
    _ => { /* required: more kinds may be added later */ }
}

The standard library does this for std::io::ErrorKind. Inside the crate that defines the enum, the attribute changes nothing, and a single-file example cannot show the effect, which is why the snippets above are read-only. Use #[non_exhaustive] on public error and option enums in libraries; do not use it on closed sets like Ordering or your own application's internal states, where exhaustive matching is exactly what you want.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is an enum with Loading, Success and Failure variants better than a struct with is_loading, body and error_code fields?

    The struct allows combinations that make no sense. The enum makes illegal states unrepresentable, and each variant carries only the data valid in that state.
  2. 2. Why does a recursive enum such as Expr need Box<Expr> for its children?

    A Box stores the child on the heap behind a fixed-size pointer, so the size of Expr is finite and known at compile time.
  3. 3. In a match, arms (Failure { code: 404 }) and (Failure { code }) both appear. Which order is correct?

    Arms are tested in order, and the first matching arm wins. A general arm placed first would hide the specific one (the compiler warns about the unreachable pattern).
  4. 4. What is the main danger of a wildcard arm (_) when matching an enum you own?

    A wildcard turns a compile error (new variant not handled) into silent default behaviour, which defeats the refactoring safety net.
  5. 5. What does #[non_exhaustive] on a public enum require from other crates?

    It signals that variants may be added in future versions, so downstream code must have a fallback arm and keeps compiling when the library adds a variant.

Summary

  • Model each case of your problem as a variant carrying only the data it needs; illegal states then cannot be built.
  • Recursive enums (expression trees) use Box for children; functions like eval and show have one arm per variant.
  • Nested and or-patterns let you write rewrite rules directly, and arms are tried top to bottom.
  • Parse text into a command enum first, execute it second.
  • A state machine is a state enum, an event enum and one match (state, event).
  • Enums fit closed sets of cases; trait objects fit open sets that others extend.
  • Avoid _ arms for growing enums so the compiler lists what to update; use #[non_exhaustive] for public library enums.

Next: Traits