Pattern Matching in Rust
Patterns destructure data and control flow via match, if let, and while let.
Destructuring
Unpack tuples, structs, and enums.
let tup = (1, 2);
let (a, b) = tup;
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
let Point { x, y: y2 } = p;
match with guards
let v = Some(10);
match v {
Some(n) if n > 5 => println!("gt5"),
Some(_) => println!("some"),
None => println!("none"),
}
Binding and @ patterns
let x = 7;
match x {
n @ 1..=9 => println!("digit {n}"),
_ => {}
}
Or-patterns and ranges
let c = 'a';
match c {
'a' | 'e' | 'i' | 'o' | 'u' => println!("vowel"),
'0'..='9' => println!("digit"),
_ => {}
}
if let / while let
Convenience when matching a single pattern.
if let Some(n) = v { println!("{n}") }
let mut it = (0..3).into_iter();
while let Some(n) = it.next() { println!("{n}") }
Ref and mut in patterns
Borrow or mutably borrow while matching.
let mut s = String::from("hi");
let r = &mut s;
match r {
ref mut m => m.push('!'),
}
Summary
- Use patterns to destructure and inspect values concisely
- Add guards, use bindings, and combine patterns for readable matches