skip to content

After a Refunded variant is added to a Rust OrderState enum, why does a match on (state, event) still compile, and how do you restructure it so rustc flags it?

level: seniorimportance: should knowfreq 45%

answer

  1. what does the last arm cover
  2. tuples are checked per combination
  3. name every state explicitly
  4. unreachable pattern warnings

basics

~20 s

Rust's tuple match still compiles because a trailing _ covers every combination, including those with OrderState::Refunded. Name every state in the first position and keep wildcards only on the event side, so a new state fails with E0004.

solid answer

~50 s

Exhaustiveness on a tuple is checked over every combination of its fields, and a final `_ => None` covers all of them, so adding `OrderState::Refunded` (or a `Refund` event) changes nothing at compile time: refunds are silently rejected at runtime. To get the compiler's help back, list **every state by name** in the first position and use `_` only for events within a state, such as `(Cancelled, _) => None`. Then a new state is reported as error `E0004`, "non-exhaustive patterns: `(OrderState::Refunded, _)` not covered". A new event is caught only in rows that list events explicitly, so keep `_` out of rows where events matter. Watch for `unreachable pattern` warnings too: a bare name that is not a variant in scope, such as a misspelt `Canceled`, is a binding that matches everything; spelled exactly like the variant, rustc rejects it with E0170.

code

rust · 23 lines
rust
#[derive(Debug, Clone, Copy, PartialEq)]
enum OrderState { Pending, Paid, Shipped, Cancelled, Refunded } // Refunded: new

#[derive(Debug, Clone, Copy)]
enum Event { Pay, Ship, Cancel, Refund } // Refund: new

fn next(state: OrderState, event: Event) -> Option<OrderState> {
    use OrderState::*;
    match (state, event) {
        (Pending, Event::Pay) => Some(Paid),
        (Paid, Event::Ship) => Some(Shipped),
        (Pending | Paid, Event::Cancel) => Some(Cancelled),
        _ => None, // swallows every new state and every new event
    }
}

fn main() {
    println!("{:?}", next(OrderState::Pending, Event::Pay));
    println!("{:?}", next(OrderState::Pending, Event::Cancel));
    // Compiles with no warning; the refund is silently rejected.
    println!("{:?}", next(OrderState::Shipped, Event::Refund));
    println!("{:?}", next(OrderState::Refunded, Event::Ship));
}

go deeper

for a junior

Recall that _ matches anything, so a new variant falls into it without any compile error.

for a middle

Explain that a tuple match is checked over every combination and how naming each state brings E0004 back.

for a senior

Diagnose a silent behaviour change from a wildcard, restructure the transition table, and treat unreachable_patterns and E0170 as real bugs.

for a principal

Decide which enums are expected to grow and where wildcards are acceptable, and make that a reviewable convention rather than an accident.

## Why the build stays green An order workflow is often written as a single `match` on a tuple of the current state and an incoming event: ```rust match (state, event) { (Pending, Event::Pay) => Some(Paid), (Paid, Event::Ship) => Some(Shipped), (Pending | Paid, Event::Cancel) => Some(Cancelled), _ => None, } ``` The exhaustiveness checker treats a tuple as the **product of its fields**: it must cover every pairing of a state with an event. The last arm, `_`, covers every pairing that the earlier arms do not. When the team adds `OrderState::Refunded` and `Event::Refund`, every new pairing, such as `(Shipped, Refund)` or `(Refunded, Ship)`, falls into `_` and returns `None`. rustc has nothing to report, because the match is still exhaustive. The new feature is wired into the enum and quietly ignored by the state machine. This is the general cost of a wildcard: **`_` matches values that did not exist when the arm was written**. On a type you own and expect to grow, that turns a compile error into a runtime behaviour change. ## Restructure so new variants surface The fix is to make the **state axis explicit** and keep wildcards only where "any event" is truly the intent: 1. Give every state at least one arm that names it in the first position. 2. Within a state, list the events that matter and group the rest with an or-pattern, such as `(Pending, Event::Ship | Event::Refund) => None`. 3. Use `(State, _)` only for states where every event, including future ones, really has the same answer, such as a terminal `Cancelled`. With that shape, rustc 1.99 reports the new state immediately: error `E0004`, "non-exhaustive patterns: `(OrderState::Refunded, _)` not covered". The message names the state and leaves the event as `_`, telling you that a whole row is missing. | Arm style | New state added | New event added | |---|---|---| | Final `_ => None` | silently `None` | silently `None` | | Every state named, events listed per state | E0004 for the state | E0004 for each row that lists events | | Every state named, `(State, _)` rows | E0004 for the state | silent in the `_` rows | A nested `match state { ... }` with an inner `match event { ... }` per state gives the same guarantees and is often easier to read when the table gets large. ## Arms that can never run The same exhaustiveness machinery reports the opposite problem, **unreachable patterns**, through the `unreachable_patterns` lint (warn by default, part of the `unused` group). It fires when an earlier arm already covers everything a later arm could match: - an arm after `_` is unreachable, with the note "no value can reach this"; - a narrower arm after a broader one, such as `(Shipped, Event::Refund)` placed after `(Shipped, _)`, is unreachable; - an arm that is just an identifier is a **binding**, which matches everything, so every arm after it is unreachable. The last case is a classic diagnosis. Writing `Cancelled => true` without `OrderState::` and without a `use OrderState::*` in scope does not name the variant; it binds a new variable called `Cancelled`. rustc 1.99 rejects that exact spelling with error `E0170`, "pattern binding `Cancelled` is named the same as one of the variants of the type `OrderState`", under the deny-by-default `bindings_with_variant_name` lint. A **misspelling** such as `Canceled` is not caught by E0170; it compiles with `unreachable pattern` and `unused variable` warnings, and the function returns `true` for every state. So an `unreachable pattern` warning in a match over an enum deserves to be treated as a bug, not as noise. ## Keeping it maintainable - Name the states; let `_` stand only for "any event, now and later". - Group the rejections per state with or-patterns so the table stays short. - Run the build with warnings visible in CI so `unreachable_patterns` is not lost. - Where a team wants this everywhere, Clippy's `wildcard_enum_match_arm` lint can flag `_` arms over enums; deciding whether to adopt it is a team policy question. - For enums from another crate marked `#[non_exhaustive]`, a wildcard is mandatory; that belongs with API evolution, not with your own types.

  • An arm reads `Canceled => true` in a match over OrderState, and every order is now terminal. What happened?
    `Canceled` is not a variant, so the pattern is a fresh binding that matches every value. rustc compiles it with `unreachable pattern` warnings on the later arms and an `unused variable` warning that suggests `OrderState::Cancelled`. Spelled exactly like the variant without the path, it is error E0170 instead.
  • Why does the E0004 message for the tuple say `(OrderState::Refunded, _)` rather than listing each event?
    The checker reports a witness pattern that covers the gap as compactly as it can. No arm mentions Refunded in the first position, so every event is uncovered for it, and `_` in the event slot says "all of them". Adding `(Cancelled | Refunded, _) => None` or a Refunded row clears it.
  • When is a `(State, _)` row the right choice?
    When every event, including events added later, should get the same answer in that state, as for a terminal Cancelled state that ignores all input. If a future event might need handling there, list the current events instead, so the new one is reported.

  • Adding a variant always breaks every match over the enum
  • A trailing _ arm is harmless because it only catches today's leftovers
  • Exhaustiveness on a tuple checks each field separately, not combinations
  • An unreachable pattern warning is cosmetic and safe to ignore
  • A bare Cancelled arm always matches the variant, even without a path