skip to content

In Rust, why does a match over an OrderState enum that leaves out Cancelled fail with E0004, and what must every arm agree on?

level: juniorimportance: must knowfreq 80%

answer

  1. every possible value needs an arm
  2. error names the missing pattern
  3. match is an expression
  4. arms share one type, E0308 otherwise

basics

~20 s

A Rust match must be exhaustive: rustc proves every value of the scrutinee's type is covered, so a missing OrderState::Cancelled arm is error E0004. Because match is an expression, every arm must also produce the same type.

solid answer

~40 s

rustc checks every `match` for **exhaustiveness**: the arms together must cover every value the scrutinee's type can hold. Leave out `OrderState::Cancelled` and the build stops with error `E0004`, "non-exhaustive patterns: `OrderState::Cancelled` not covered", naming the missing pattern and suggesting an arm. You fix it by adding an arm for that variant, or a trailing `_` arm if you really mean "everything else". Because `match` is an **expression**, the value it produces has one type, so every arm must evaluate to that type; an arm returning `&str` where the others return integers is `E0308`, "`match` arms have incompatible types". A diverging arm such as `panic!()` or `unreachable!()` has type `!` and fits anywhere.

code

rust · 20 lines
rust
#[derive(Debug, Clone, Copy)]
enum OrderState {
    Pending,
    Paid,
    Shipped,
    Cancelled,
}

fn label(state: OrderState) -> &'static str {
    // Meant to fail: Cancelled has no arm.
    match state {
        OrderState::Pending => "awaiting payment",
        OrderState::Paid => "ready to pack",
        OrderState::Shipped => "on its way",
    }
}

fn main() {
    println!("{}", label(OrderState::Cancelled));
}

go deeper

for a junior

Recall that every match must cover all values of its type, that a missing variant is E0004, and that the error names the pattern you forgot.

for a middle

Explain that match is an expression, so all arms share one type, why a panic! arm still fits, and why the wildcard must come last.

for a senior

Show that you choose explicit arms over _ on your own enums because the E0004 at each match site is how a new variant gets reviewed.

for a principal

Frame exhaustiveness as a cheap, compiler-enforced review checklist, and say where a team would rather trade it for less noise, such as integer or string scrutinees.

## What rustc checks on every `match` A `match` expression takes a value, the **scrutinee**, and compares it against a list of **arms**, each a pattern followed by `=>` and an expression. The arms are tried top to bottom and the first one whose pattern matches is chosen. Before any of that can run, the compiler insists on two properties: 1. **Exhaustiveness** — the patterns, taken together, must cover every value the scrutinee's type can hold. If even one value could fall through every arm, the program is rejected. 2. **One result type** — the whole `match` is an expression that evaluates to the chosen arm's value, so all arms must produce values of the same type. Both are compile-time checks. There is no runtime "no arm matched" path for a `match` that compiled, which is exactly why the compiler is strict about it. ## E0004: a variant without an arm Take an order-state machine with four states: ```rust enum OrderState { Pending, Paid, Shipped, Cancelled } fn label(state: OrderState) -> &'static str { match state { OrderState::Pending => "awaiting payment", OrderState::Paid => "ready to pack", OrderState::Shipped => "on its way", } } ``` rustc 1.99 refuses it with error `E0004`, "non-exhaustive patterns: `OrderState::Cancelled` not covered". The diagnostic is practical: - it **names the missing pattern** (here `OrderState::Cancelled`), and points at the variant in the enum definition; - it prints the scrutinee's type (`the matched value is of type `OrderState``); - it suggests an arm, either the explicit pattern or a wildcard, with `todo!()` as a placeholder body. The error-code index describes E0004 as the compiler being unable to guarantee a matching pattern for one or more possible inputs, and recommends covering enums with few variants explicitly, with a trailing `_` as the alternative. ## The two ways to fix it | Fix | What you write | What happens when a fifth variant is added | |---|---|---| | Explicit arm | `OrderState::Cancelled => "cancelled"` | The next build fails again with E0004 at this match | | Wildcard arm | `_ => "cancelled"` | The new variant silently takes this arm | Both make the match exhaustive. The explicit arm is usually the better choice for your own enums: the error you just fixed is the compiler telling you where a new state needs a decision, and a wildcard switches that signal off for this match. A `_` arm is natural where listing values is impossible or pointless, such as matching on a `u16`, a `String` or a foreign enum. The arm order matters for the wildcard: `_` must come **last**. Any arm placed after it can never run, and rustc warns `unreachable pattern` with the note "no value can reach this". ## Match is an expression, so arms must agree Because a `match` produces a value, you can write `let days = match state { ... };` or use it as a function's tail expression. That value has one type, so: - every arm's expression must have the same type (or coerce to it); - an arm returning `"in transit"` while the others return `0` and `1` is error `E0308`, "`match` arms have incompatible types", and rustc labels each arm's type in the message; - an arm whose block ends in a statement, such as `{ total += 1; }`, evaluates to `()`, which clashes with arms that produce a value. **Diverging arms** are the exception that makes this comfortable. `panic!()`, `unreachable!()`, `todo!()`, `return` and `continue` never produce a value; their type is `!`, the never type, and `!` coerces to any type. So `OrderState::Cancelled => panic!("no delivery for a cancelled order")` sits happily beside arms that return `u32`. That is a deliberate choice, though: it moves the check from compile time to a runtime panic. ## What exhaustiveness covers beyond enums Exhaustiveness is checked for every type, not only enums: - `bool` needs both `true` and `false` (or a `_`); - `Option<T>` needs `Some(..)` and `None`; the Book's own E0004 example is a forgotten `None`; - integers can be covered by ranges, as in `0..=u8::MAX`; - tuples and structs are covered field by field, so a match on `(state, event)` must cover every combination. The rule is the same everywhere: if the compiler can construct a value no arm accepts, it prints that value in the E0004 message. Reading that pattern is usually the fastest way to see which case you forgot.

  • What happens if you put the `_` arm first in that match?
    It still compiles, because the match is exhaustive, but `_` matches every value, so every arm after it is dead. rustc warns `unreachable pattern` on each later arm with the note "no value can reach this". Arms are tried in order, so a catch-all belongs last.
  • Why does an arm that calls `panic!()` not break the "arms must agree on a type" rule?
    `panic!()` never returns, so its type is the never type `!`, and `!` coerces to any type. The same holds for `unreachable!()`, `todo!()`, `return` and `continue`. The arm type-checks, but you have traded a compile-time check for a runtime panic if that state ever arrives.
  • Does E0004 apply to `bool` and `Option`, or only to your own enums?
    To every type. A `match` on a `bool` with only a `true` arm fails with E0004 naming `false`, and a `match` on an `Option` without `None` fails naming `None`. For integers, the message names the uncovered range, such as `0_u16..=99_u16`.

  • A non-exhaustive match compiles and panics at runtime when no arm fits
  • Exhaustiveness checking applies only to enums, not to bool or integers
  • Arms of one match may return different types if the match is not assigned
  • A wildcard arm placed first still lets later specific arms run
  • Adding _ and adding the explicit variant arm behave the same forever