capypad
0 Tage Serie
rust / beginner
Snippet

Musterabgleich mit match

Das match-Schlüsselwort ermöglicht Musterabgleich gegen Werte. Es vergleicht die Eingabe mit jedem Muster und führt den Code des ersten übereinstimmenden Zweigs aus. Der Unterstrich _ ist ein Platzhalter, der alles andere abdeckt.

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));
}
Erklärung
1
match score { ... }
Startet den Musterabgleich mit der Variable score
2
0 => "No points",
Exakte Übereinstimmung für score von 0
3
1..=50 => "Keep practicing!"
Bereichsmuster für Scores von 1 bis 50
4
_ => "Invalid score"
Platzhalter-Zweig für alle weiteren Werte