if / else if / else in Rust
Branching where every branch is an expression.
fn classify(n: i32) -> &'static str {
if n < 0 {
"negative"
} else if n == 0 {
"zero"
} else if n % 2 == 0 {
"positive even"
} else {
"positive odd"
}
}
fn main() {
let label = classify(7);
println!("{label}");
}
How it works
- The
ifladder returns at the first true arm. - Each arm yields the same
&'static strtype. - The whole
ifis the function's return value.
Keywords and builtins used here
classifyelsefni32ifletmainstaticstr
The run, in numbers
- Lines
- 16
- Characters to type
- 213
- Tokens
- 74
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 52 seconds.
Step 1 of 8 in Control flow, step 11 of 39 in Language basics.