capypad
0 day streak
rust / beginner
Snippet

Pattern Matching with match

The match keyword allows pattern matching against values. It compares the input against each pattern and executes the code for the first matching branch. The underscore _ is a wildcard that matches anything else.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn describe_score(score: u8) -> &'static str {
match score {
0 => "No points",
1..=50 => "Keep practicing!",
51..=100 => "Good job!",
_ => "Invalid score",
}
}
 
 
fn main() {
println!("Score 25: {}", describe_score(25));
println!("Score 75: {}", describe_score(75));
}
Breakdown
1
match score { ... }
Starts pattern matching on the score variable
2
0 => "No points",
Exact match for score of 0
3
1..=50 => "Keep practicing!"
Range pattern matching scores 1 through 50
4
_ => "Invalid score"
Wildcard branch catches all remaining values