match expressions in Rust
Exhaustive pattern matching over a value.
fn describe(n: i32) -> String {
match n {
0 => "zero".to_string(),
1 | 2 | 3 => "small".to_string(),
4..=9 => "medium".to_string(),
_ if n < 0 => "negative".to_string(),
_ => "large".to_string(),
}
}
fn main() {
println!("{}", describe(7));
}
How it works
- Literal, or-pattern, and range arms match values.
- A guard
if n < 0refines an arm. _is the catch-all; match must be exhaustive.
Keywords and builtins used here
Stringdescribefni32ifmainmatch
The run, in numbers
- Lines
- 13
- Characters to type
- 243
- Tokens
- 98
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.
Step 1 of 4 in Pattern matching, step 19 of 39 in Language basics.