Rust:Rust Exhaustive Match Pattern Matching and Expression Control Flow
Rust•Conditionals

Rust Exhaustive Match Pattern Matching and Expression Control Flow

In Rust, match is an expression that yields values directly. Unlike switch statements in C-style languages, Rust match expressions are strictly exhaustive: the compiler guarantees that every possible variant or value is explicitly handled. Combined with match guards (if condition), inclusive range patterns (..=), and destructuring, match provides bulletproof, branch-safe flow control.

Syntax

let status = match code { 200 | 201 => "SUCCESS", 400..=499 => "CLIENT_ERROR", _ => "OTHER", };

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
match exprExpressionEvaluates value against multiple patterns and returns result of matching arm.
_Wildcard DiscardMatches any remaining values, fulfilling compiler exhaustiveness checking.
Match GuardConditionAn extra if condition added to a match arm (e.g. n if n > 100 => ...).

Ready-to-Run Code Example

Executable in Compilra

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

fn main() {
    let test_status_codes = [200, 304, 404, 503, 999];

    println!("=== Rust Exhaustive Pattern Matching Engine ===");

    for &code in &test_status_codes {
        // 1. Expression-driven exhaustive match returning &str
        let category = match code {
            200 | 201 | 204 => "Fast-Path Success (2xx)",
            301 | 302 | 304 => "Cache / Redirect (3xx)",
            400..=499 => "Client Parameter Fault (4xx)",
            500..=599 => "Server Upstream Failure (5xx)",
            _ => "Unclassified Protocol Code", // Exhaustive catch-all
        };

        // 2. Pattern matching with conditional match guard
        let action = match code {
            c if c == 200 => "Forward payload directly to consumer",
            c if c >= 500 => "Trigger incident response alert to SRE team",
            _ => "Log standard diagnostic audit event",
        };

        println!("Status Code [{}]: {:<30} | Action: {}", code, category, action);
    }
}
Expected Output:
=== Rust Exhaustive Pattern Matching Engine ===
Status Code [200]: Fast-Path Success (2xx)        | Action: Forward payload directly to consumer
Status Code [304]: Cache / Redirect (3xx)         | Action: Log standard diagnostic audit event
Status Code [404]: Client Parameter Fault (4xx)   | Action: Log standard diagnostic audit event
Status Code [503]: Server Upstream Failure (5xx)  | Action: Trigger incident response alert to SRE team
Status Code [999]: Unclassified Protocol Code     | Action: Log standard diagnostic audit event

How It Works: Step-by-Step

  • Lines 8-15: Evaluates code against multiple literals (|), inclusive ranges (400..=499), and wildcard (_).
  • Lines 18-22: Demonstrates match guards (c if c >= 500) for custom boolean criteria.
  • Line 24: Prints evaluated category and action directly from expression return bindings.

Key Concepts

  • Every match arm must evaluate to the same return type, ensuring type soundness.
  • Rust compilers verify exhaustiveness: omitting a possible scenario without the _ wildcard triggers a compile-time error.
  • Inclusive ranges like 400..=499 match any integer from 400 up to and including 499.
  • Multiple patterns can be chained in a single arm using the pipe (|) operator.

Common Mistake: Non-exhaustive patterns error in match expressions

Forgetting to cover all possible integer values or omitting the _ fallback pattern prevents compilation.

❌ Incorrect
let res = match x { 1 => "One", 2 => "Two" }; // Compile Error: pattern `_` not covered
✅ Correct
let res = match x { 1 => "One", 2 => "Two", _ => "Other" }; // Correct: exhaustive

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