pattern

Rust Match guards for additional conditions

A guard adds a Boolean condition after a pattern matches. If it is false, matching continues with later arms. Expected output (not executed): bulk Why: The pattern extracts 12, and the guard accepts it. Common mistake: Guarded arms do not count as covering all values for exhaustiveness; keep an unguarded fallback.

Formal Syntax & Structure

rust syntaxrust
pattern if boolean_condition => expression

Working Example

Example Snippetrust
fn main() {    let quantity = Some(12);    let label = match quantity {        Some(n) if n >= 10 => "bulk",        Some(_) => "regular",        None => "missing",    };    println!("{label}");}
Rust Reference