Pattern Matching (Rust)
Pattern matching destructures values to test their shape and bind their parts to variables. It powers match, if let, while let, and even let and function parameters in Rust.
Rust
A pattern describes the structure of a value: literals, variable bindings, tuples, struct fields, enum variants, ranges, and wildcards (_). When a value matches, the named parts are bound to new variables you can use in that branch.
Patterns appear in more than just match: if let runs a block only when one pattern fits, while let loops while it does, and you can destructure directly in let bindings and function arguments — let (a, b) = pair;.
Guards (if condition after a pattern), the | operator for alternatives, and ranges (1..=5) make patterns expressive. Pattern matching plus enums is the backbone of idiomatic Rust modeling.
Syntax
if let Some(x) = maybe { use(x); }
let (a, b) = (1, 2);Examples
Rust
fn main() {
let point = (0, 7);
match point {
(0, y) => println!("on y-axis at {}", y),
(x, 0) => println!("on x-axis at {}", x),
(x, y) => println!("({}, {})", x, y),
}
}Output:
on y-axis at 7