typestar

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

  1. A block's last expression, without a semicolon, is its value.
  2. if in a let replaces the ternary operator.
  3. A semicolon turns an expression into a statement worth nothing.

Keywords and builtins used here

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.

Type this snippet

Step 7 of 8 in Control flow, step 17 of 39 in Language basics.

← Previous Next →