Pattern Matching
Match with guards
Arms can include extra conditions.
let n = 7;
match n {
1..=5 => println!("small"),
x if x % 2 == 0 => println!("even"),
_ => println!("other"),
}
if let for one case
Use when you only care about one pattern.
let value = Some(3);
if let Some(n) = value {
println!("{n}");
}
Destructure structs
Pull fields out in a match or let pattern.
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
let Point { x, y } = p;
println!("{x},{y}");
Matching tips
matchmust be exhaustive- Use
_for values you intentionally ignore - Prefer readable arms over clever nested patterns
- Combine with enums for clear control flow
Comments
One comment per signed-in account. Comments are saved with this page’s URL.