21.5 match
Expressions
The match
expression is Rust’s primary tool for complex pattern matching. It evaluates an expression and executes the code associated with the first matching pattern arm.
match VALUE_EXPRESSION {
PATTERN_1 => CODE_BLOCK_1,
PATTERN_2 => CODE_BLOCK_2,
// ...
PATTERN_N => CODE_BLOCK_N,
}
21.5.1 Example: Matching Option<T>
Handling optional values is a classic use case:
fn check_option(opt: Option<&str>) { match opt { Some(message) => { println!("Received message: {}", message); } None => { println!("No message received."); } } } fn main() { check_option(Some("Processing Data")); // Output: Received message: Processing Data check_option(None); // Output: No message received. }
The compiler ensures all possibilities (Some
and None
) are handled, guaranteeing exhaustiveness.