rust / beginner
Snippet
Pattern Matching with match Expressions
The match expression compares a value against multiple patterns and executes the first matching arm. It must be exhaustive, meaning all possible cases must be covered. The underscore _ acts as a catch-all pattern for any value not matched by previous arms.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
fn main() {let number = 7;match number {1 => println!("One"),2 => println!("Two"),3 => println!("Three"),4..=10 => println!("Between four and ten"),_ => println!("Something else"),}}
Breakdown
1
fn main() {
Entry point of the program where execution begins
2
let number = 7;
Immutable variable binding storing the integer value 7
3
match number {
Starts pattern matching on the 'number' variable
4
1 => println!("One"),
If number equals 1, prints 'One'
5
2 => println!("Two"),
If number equals 2, prints 'Two'
6
3 => println!("Three"),
If number equals 3, prints 'Three'
7
4..=10 => println!("Between four and ten"),
Range pattern matching numbers 4 through 10 inclusive
8
_ => println!("Something else"),
Catch-all pattern for any value not matched above