Everything is an expression in Rust
Blocks, ifs and matches all evaluate to a value, which is why Rust needs few statements.
fn main() {
let score = 87;
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else {
"C"
};
let adjusted = {
let bonus = 5;
score + bonus
};
println!("{grade} {adjusted}");
}
How it works
- A block's last expression, without a semicolon, is its value.
ifin aletreplaces the ternary operator.- A semicolon turns an expression into a statement worth nothing.
Keywords and builtins used here
elsefnifletmain
The run, in numbers
- Lines
- 18
- Characters to type
- 190
- Tokens
- 63
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 44 seconds.
Step 7 of 8 in Control flow, step 17 of 39 in Language basics.