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:
| Parameter | Type | Description |
|---|---|---|
| _ | Wildcard | Matches any remaining uncovered value. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Rust Exhaustive Match Pattern Matching and Expression Control Flow
Master expression-driven pattern matching in Rust using exhaustive match blocks, match guards, range patterns (..=), and wildcards (_).
Rust Zero-Cost Sequence Parsing Iterators and For Loops
Master Rust zero-cost iterator loops: borrowed iteration (&vec), iterator adapters (filter, count), and value-returning infinite loop expressions.
Rust Functions and Implicit Expression Block Return Optimization
Master Rust expression-oriented functions: implicit tail returns (omitting semicolon), explicit return keyword, and block optimization schemas.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.