Pattern matching is a powerful feature for destructuring and checking values. It goes beyond just enums—you can match on structs, tuples, arrays, and more.
Basic Match Syntax
match is exhaustive—all possibilities must be handled:
match value {
pattern1 => result1,
pattern2 => result2,
_ => default_result, // Catch-all
}
fndescribe_value(value: i32) {
match value {
n if n < 0 => println!(\"Negative: {}\", n),
n if n == 0 => println!(\"Zero\"),
n if n % 2 == 0 => println!(\"Even: {}\", n),
_ => println!(\"Odd positive\"),
}
}
Combining Patterns
Multiple patterns in one arm:
fndemo(value: i32) {
match value {
1 | 3 | 5 => println!(\"Odd single digit\"),
2 | 4 | 6 => println!(\"Even single digit\"),
_ => println!(\"Something else\"),
}
}
Range Patterns
fndemo(value: i32) {
match value {
1..=5 => println!(\"One through five\"),
6..=10 => println!(\"Six through ten\"),
_ => println!(\"Other\"),
}
}
Practical Example
structUser {
name: String,
age: u32,
}
fncategorize_user(user: Option<User>) {
match user {
Some(User { name, age }) if age >= 18 => {
println!(\"{} is an adult\", name);
}
Some(User { name, age }) => {
println!(\"{} is a minor ({})\", name, age);
}
None => println!(\"No user\"),
}
}
Pattern Matching Benefits
Exhaustiveness: Compiler ensures all cases handled
Safety: Can't access wrong fields by mistake
Expressiveness: Complex logic becomes readable
Type safety: Pattern matching respects types
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities