match Expression (Rust)
match compares a value against a series of patterns and runs the arm of the first one that fits. It is an expression (returns a value) and must be exhaustive — every possible case has to be covered.
Rust
match is Rust's most powerful control-flow tool. Each arm is pattern => expression, and the compiler checks that the patterns cover every possibility; if you miss a case it won't compile. Use _ as a catch-all wildcard.
Because patterns can destructure, a single match can pull data out of enums, tuples, and structs while branching. This is what makes Option and Result so ergonomic — you match Some/None or Ok/Err and bind the inner value in one step.
match is an expression, so its result can be assigned to a variable. For matching just one pattern, the lighter if let is often cleaner; reach for match when you have several cases or need exhaustiveness checking.
Syntax
match value {
pattern1 => expr1,
pattern2 if guard => expr2,
_ => default,
}Examples
Rust
fn main() {
let n = 3;
let word = match n {
1 => "one",
2 | 3 => "a few",
_ => "many",
};
println!("{}", word);
}Output:
a few