skip to content

In Rust, what do `c @ 400..=499` and `Some(Paid | Shipped)` do as match patterns, and when is `matches!` the better tool?

level: middleimportance: should knowfreq 50%

answer

  1. name a value while testing it
  2. or-patterns nest inside constructors
  3. every alternative binds the same names
  4. matches! returns bool, bindings stay inside

basics

~20 s

In Rust, c @ 400..=499 tests the value against the range and binds it to c; Some(Paid | Shipped) is a nested or-pattern matching either variant inside Some. matches!(value, pattern) returns a bool when you need only the test.

solid answer

~40 s

An **`@` binding**, `name @ subpattern`, matches the subpattern and binds the whole matched value to `name`, so `c @ 400..=499` gives the arm the actual status code, not just the fact that it was in range. An **or-pattern** `p | q` matches either alternative, and it can be nested inside constructors: `Some(Paid | Shipped)` means the same as `Some(Paid) | Some(Shipped)`. Every alternative must bind the same names with the same types, and `|` has the lowest precedence, so `c @ 301 | 302` is `(c @ 301) | 302` and fails with E0408; write `c @ (301 | 302)`. **`matches!(expr, pattern)`** expands to a `match` that yields `true` or `false`, accepts an optional `if` guard, and its bindings do not escape the macro, so it fits predicates like `can_refund`.

code

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

fn describe(code: u16) -> String {
    match code {
        c @ (301 | 302 | 307 | 308) => format!("redirect {c}, follow Location"),
        c @ 400..=499 => format!("client error {c}"),
        c @ 500.. => format!("server error {c}"),
        c => format!("status {c}"),
    }
}

fn can_refund(state: Option<OrderState>) -> bool {
    matches!(state, Some(OrderState::Paid | OrderState::Shipped))
}

fn main() {
    for code in [307, 429, 503, 204] {
        println!("{}", describe(code));
    }
    for s in [OrderState::Pending, OrderState::Paid, OrderState::Shipped, OrderState::Cancelled] {
        println!("{s:?}: {}", can_refund(Some(s)));
    }
    println!("None: {}", can_refund(None));
}

go deeper

for a junior

Recall that | lets one arm match several values and that matches! returns true or false for a pattern.

for a middle

Explain name @ subpattern, nested or-patterns like Some(A | B), the same-bindings rule, and why c @ 301 | 302 needs parentheses.

for a senior

Prefer @ and ranges over guards to keep arms visible to the exhaustiveness checker, and notice that matches! hides a _ => false.

for a principal

Weigh the readability of matches! predicates against the wildcard they hide, and decide where your own enums deserve a full match instead.

## Binding a value while you test it: `@` A pattern usually either **tests** a value (a literal, a range, a variant) or **binds** it (an identifier like `c`). An **`@` binding** does both: `name @ subpattern` matches only if the subpattern matches, and then binds the whole value to `name`. ```rust match code { c @ 400..=499 => format!("client error {c}"), c @ 500.. => format!("server error {c}"), c => format!("status {c}"), } ``` Without `@` you would have to choose: `400..=499 =>` knows the class but not the code, and `c =>` knows the code but tests nothing. With a guard you could write `c if (400..=499).contains(&c)`, but then the arm stops counting toward exhaustiveness. The `@` form keeps the test in the pattern, where the checker can see it. The subpattern after `@` may itself bind names (stable since Rust 1.56), for example `whole @ Some(inner)`. ## Or-patterns, top-level and nested An **or-pattern** `p | q` matches when either alternative matches. At the top of an arm, `OrderState::Paid | OrderState::Shipped => ...` lets one body handle two variants. Since Rust 1.53, `|` can also appear **inside** a pattern: | Written | Equivalent to | |---|---| | `Some(Paid | Shipped)` | `Some(Paid) | Some(Shipped)` | | `(Pending | Paid, Event::Cancel)` | `(Pending, Event::Cancel) | (Paid, Event::Cancel)` | | `c @ (301 | 302 | 307 | 308)` | four arms that each bind `c` | For exhaustiveness, the Reference states a distributive law: `c(p | q, ..rest)` covers the same values as `c(p, ..rest) | c(q, ..rest)`. Nesting is just a shorter way to write the same set. Three rules keep or-patterns honest: 1. **Every alternative must bind the same set of names**, each with the same type and binding mode. Otherwise the arm body could read a name that was never bound. 2. **`|` has the lowest precedence of any pattern operator.** `c @ 301 | 302` parses as `(c @ 301) | 302`, so the second alternative binds nothing. rustc 1.99 reports error `E0408`, "variable `c` is not bound in all patterns". The fix is parentheses: `c @ (301 | 302)`. 3. **A guard covers the whole or-pattern**: `301 | 302 if follow => ...` is `(301 | 302) if follow`. Or-patterns are also the tool that keeps a match **explicit without repetition**. Writing `OrderState::Pending | OrderState::Cancelled => false` instead of `_ => false` gives the same behaviour today, but when a fifth variant is added the match stops being exhaustive and rustc reports E0004 at exactly this arm. The cost is one line naming the variants; the benefit is that the compiler keeps asking the question for you. ## `matches!`: a match that answers yes or no Many matches exist only to produce a `bool`: ```rust match state { Some(OrderState::Paid | OrderState::Shipped) => true, _ => false, } ``` `core::matches!` is that shape as a macro. Its definition in `core/src/macros/mod.rs` is a `macro_rules!` that expands `matches!(expr, pattern if guard)` to a `match` with your pattern (and optional guard) yielding `true` and `_ => false`. So: - `matches!(state, Some(OrderState::Paid | OrderState::Shipped))` is the whole `can_refund` predicate; - the pattern syntax is exactly that of a match arm, including ranges, or-patterns and `@`; - an optional guard is allowed: `matches!(x, Some(n) if n > 2)`; - names bound in the pattern exist **only inside the macro**, so using `n` after `matches!(x, Some(n) if n > 2)` is `E0425`, "cannot find value `n` in this scope". Clippy's `match_like_matches_macro` lint, warn by default, suggests the macro whenever it sees the `=> true, _ => false` shape. ## Choosing between them - Need the value in the body: use `@` (`c @ 500..`) or a plain binding. - Several variants share one body: an or-pattern, nested where it removes repetition. - Need only a `bool` for an `if`, a `filter` or a predicate function: `matches!`. - Need to assert a shape in a test: the testing material covers `assert_matches!`, which prints the value when the pattern does not match. One caution carries over from the wildcard discussion: `matches!` always contains a hidden `_ => false`. A new variant added to `OrderState` silently makes such a predicate return `false`, and no E0004 will point at it.

  • Why is `c @ (301 | 302)` accepted while `c @ 301 | 302` is not?
    `|` has the lowest precedence in patterns, so the unparenthesised form is `(c @ 301) | 302`, and the `302` alternative binds nothing. Every alternative must bind the same names, so rustc reports E0408. Parentheses put both literals under the `@`, so `c` is bound either way.
  • Can the names bound inside `matches!` be used after it?
    No. `matches!` expands to a `match` whose arm body is just `true`, so a binding like `n` in `matches!(x, Some(n) if n > 2)` is visible only in the guard. Using `n` afterwards is E0425. If you need the value, write an `if let` or a full `match`.

  • c @ 301 | 302 binds c for both status codes
  • Or-patterns can only appear at the top level of a match arm
  • Values bound inside matches! are available in the following statements
  • @ turns an arm into a guard that does not count toward exhaustiveness
  • Alternatives of an or-pattern may bind different variable names