Rust:Rust Match Pattern Matching: Exhaustive and Expressive
Rust•Pattern Matching

Rust Match Pattern Matching: Exhaustive and Expressive

Rust match checks all possible cases at compile time, guaranteeing no unhandled scenarios.

Syntax

match value { pat1 => res1, _ => fallback, }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
_WildcardMatches any remaining uncovered value.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    let http_status = 200;

    let response = match http_status {
        200 => "200 OK: Request succeeded",
        301 | 302 => "Redirect: Resource moved",
        400..=499 => "Client Error: Verify request parameters",
        500..=599 => "Server Error: Downstream service failure",
        _ => "Unrecognized HTTP Status",
    };

    println!("Status Evaluation: {}", response);
}
Expected Output:
Status Evaluation: 200 OK: Request succeeded

How It Works: Step-by-Step

  • Lines 4-10: Matches integer against literals, alternatives (|), ranges (..=), and wildcard (_).

Key Concepts

  • match in Rust must be exhaustive; every possible value must be handled.
  • Ranges like 400..=499 match inclusive integer bounds.
  • match unpacks enum variants and tuples cleanly.

Common Mistake: Non-exhaustive match without covering all cases

Omitting cases or the _ wildcard fails compilation with non-exhaustive patterns error.

❌ Incorrect
match num { 1 => "One" } // Compile Error: non-exhaustive patterns: `_` not covered
✅ Correct
match num { 1 => "One", _ => "Other" }

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler