typestar

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

  1. The if ladder returns at the first true arm.
  2. Each arm yields the same &'static str type.
  3. The whole if is the function's return value.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 8 in Control flow, step 11 of 39 in Language basics.

← Previous Next →