skip to content

In Rust, why does a u16 status-code match written with guards fail with E0004 when the same split into range patterns compiles?

level: middleimportance: must knowfreq 65%

answer

  1. guards are runtime conditions
  2. the checker reads patterns only
  3. integer ranges count toward coverage
  4. exclusive ranges stable since 1.80

basics

~20 s

Rust's exhaustiveness checker ignores guards: a guarded arm counts as covering nothing, so guard-only arms over a u16 leave every value uncovered. Range patterns such as 500..600 are patterns, so rustc can prove they cover the type.

solid answer

~40 s

A guard is an arbitrary boolean expression evaluated at runtime, so rustc's **exhaustiveness checker treats a guarded arm as covering nothing**; the E0004 message even says "match arms with guards don't count towards exhaustivity". Five arms like `c if c < 300` therefore leave `0_u16..=u16::MAX` uncovered. **Range patterns** are patterns, not code, and integer types are checked for exhaustiveness, so `100..200`, `200..300` and so on, plus a final `_` or `600..`, let the compiler prove coverage. Exclusive range patterns (`a..b`) are stable since Rust 1.80; before that only inclusive (`a..=b`, `..=b`) and open (`a..`) range patterns were allowed. rustc also lints range mistakes: `non_contiguous_range_endpoints` for a one-value gap after an exclusive range and `overlapping_range_endpoints` for a shared endpoint, both warn by default.

code

rust · 14 lines
rust
fn class(code: u16) -> &'static str {
    // Meant to fail: guards never count towards exhaustiveness.
    match code {
        c if c < 200 => "informational",
        c if c < 300 => "success",
        c if c < 400 => "redirect",
        c if c < 500 => "client error",
        c if c >= 500 => "server error",
    }
}

fn main() {
    println!("{}", class(404));
}

go deeper

for a junior

Recall that a guard is the if after a pattern and that range patterns like 400..=499 match integers.

for a middle

Explain why guarded arms count as covering nothing, how integer ranges make a match exhaustive, and the difference between .. and ..=.

for a senior

Read E0004's uncovered ranges as the gaps in your logic, and treat non_contiguous_range_endpoints and overlapping_range_endpoints warnings as bugs in review.

for a principal

Argue for expressing fixed value sets as patterns so the compiler keeps checking them, and keep guards for runtime relations the type system cannot see.

## Guards and exhaustiveness A **match guard** is an `if` condition after an arm's pattern: `c if c < 300 => "success"`. When the pattern matches, the guard runs; if it is `false`, matching continues with the next arm. Guards can call functions, read other variables and do anything a boolean expression can. That flexibility is why the **exhaustiveness checker ignores them**. The checker works on patterns, which describe sets of values the compiler can reason about. A guard is code, and in general the compiler cannot know what it returns. So, for the purpose of proving coverage, a guarded arm is treated as if it covered **no values at all**. The Book says it directly: the compiler does not try to check for exhaustiveness when match guard expressions are involved. The HTTP status classifier shows the consequence: ```rust match code { c if c < 200 => "informational", c if c < 300 => "success", c if c < 400 => "redirect", c if c < 500 => "client error", c if c >= 500 => "server error", } ``` A human sees that `c < 500` and `c >= 500` together cover everything. rustc 1.99 reports error `E0004`, "non-exhaustive patterns: `0_u16..=u16::MAX` not covered", with the note "match arms with guards don't count towards exhaustivity". The uncovered range is the **entire** type, because none of the five arms counts. ## Range patterns are patterns The fix is to move the condition into the pattern, where the checker can see it. Integer and `char` types support **range patterns**: | Pattern | Matches | Available since | |---|---|---| | `200..=299` | 200 through 299 inclusive | long-standing | | `200..300` | 200 through 299 (end excluded) | Rust 1.80 | | `500..` | 500 up to `u16::MAX` | Rust 1.55 | | `..=99` | 0 through 99 for `u16` | Rust 1.66 | Integer patterns take part in exhaustiveness checking (since Rust 1.33), so a set of ranges that covers `0..=u16::MAX` makes the match exhaustive without a wildcard. The classifier becomes: - `100..200`, `200..300`, `300..400`, `400..500`, `500..600` for the five classes; - `_ => "not a status code"` for everything else, or `0..100` and `600..` if you prefer to list it. Remove the wildcard and the E0004 message turns precise: `0_u16..=99_u16` and `600_u16..=u16::MAX` not covered. That is the checker doing real work: it computed the gaps between your ranges. ## The lints that catch range slips Ranges invite off-by-one errors, and rustc watches for two of them: - **`non_contiguous_range_endpoints`** (warn by default): `200..299` followed by `300..=399` leaves 299 matched by neither. rustc says "multiple ranges are one apart" and suggests the inclusive form `200_u16..=299_u16`. - **`overlapping_range_endpoints`** (warn by default): `200..=300` followed by `300..=399` both claim 300; the first arm wins, and the lint notes "you likely meant to write mutually exclusive ranges". Both are warnings, not errors, because the match is still exhaustive; the code just may not mean what it says. Treat them as bugs in review. ## When a guard is still the right tool Guards remain useful when the condition is not a fixed set of values: 1. **Relations between bindings**, such as `(a, b) if a == b`. 2. **Runtime data**, such as a configured threshold or a parsed header. 3. **Conditional destructuring**: since Rust 1.95 a guard can be an `if let`, for example `429 | 503 if let Some(h) = retry_after => ...`. Two details matter when you do use one: - The guard applies to the **whole or-pattern**: `429 | 503 if cond` means `(429 | 503) if cond`, not `429 | (503 if cond)`. - A guarded arm never helps exhaustiveness, so a match with guards needs an unguarded arm (often the same pattern without the guard, or a `_`) that covers whatever the guards reject. A common, checker-friendly shape combines both: the pattern carries the fixed part and the guard only the runtime part, as in `500..600 if retries_left > 0 => retry()`, followed by an unguarded `500..600 => fail()`. The second arm keeps the 5xx range covered whatever the guard decides, so the match stays exhaustive and every server error still lands in a known arm. ## A short review checklist - Prefer range or literal patterns when the condition is a fixed set of values. - Use `..=` when the upper bound belongs to the class; `..` (Rust 1.80+) when the next class starts there. - Read E0004's uncovered ranges literally; they are the gaps. - Treat the two range lints as defects, not noise.

  • What does rustc say if you write `200..299` followed by `300..=399`?
    It warns "multiple ranges are one apart" under the `non_contiguous_range_endpoints` lint, which is on by default: 299 is matched by neither range because `..` excludes its end. It suggests `200_u16..=299_u16`. The code still compiles, and 299 falls through to the next arm.
  • Can a guard use pattern matching itself, for example on a header value?
    Yes, since Rust 1.95 a guard may be an `if let`, as in `429 | 503 if let Some(h) = header => ...`; the arm runs only when that inner pattern matches too. Like any guard, it does not count toward exhaustiveness, so a later arm must still cover 429 and 503.
  • In `429 | 503 if retryable => ...`, which values does the guard apply to?
    Both. A guard applies to the whole or-pattern, so it reads as `(429 | 503) if retryable`. If the guard is false, matching moves on to the next arm for either value.

  • rustc understands that c < 500 and c >= 500 guards cover every value
  • Integer matches always need a _ arm because ranges cannot be exhaustive
  • In a range pattern, 200..300 includes 300
  • A guard on 429 | 503 applies only to the last alternative
  • Exclusive range patterns are still a nightly-only feature

Assumes Rust 1.99; exclusive range patterns are stable since 1.80 and if let guards since 1.95.