rust / beginner
Snippet
Pattern Matching with match
The match expression compares a value against multiple patterns and executes the first matching arm. It must be exhaustive, covering all possible values with a wildcard _ pattern. You can use ranges (2..=5), guards (if condition), and capture variables (n).
snippet.rs
1
2
3
4
5
6
7
8
9
10
fn main() {let number = 7;match number {1 => println!("One"),2..=5 => println!("Two to Five"),n if n % 2 == 0 => println!("Even number"),_ => println!("Other: {}", number),}}
Breakdown
1
match number {
Starts pattern matching on the number variable
2
1 => println!("One"),
Matches literal value 1 exactly
3
2..=5 => println!("Two to Five"),
Matches any value from 2 to 5 inclusive
4
n if n % 2 == 0 => println!("Even number"),
Guard pattern: captures value and checks condition
5
_ => println!("Other: {}", number),
Wildcard catches all remaining cases