Skip to main content

Control flow: if, loop, while, for

`if` in Rust is an expression: it produces a value, so you can bind its result directly with `let`. There is no ternary operator because none is needed. Both branches must have the same type, which the compiler checks.

There are three loops. `loop` runs until you `break` — and `break` can carry a value out. `while` checks a condition first. `for` iterates anything iterable, which in practice is what you want almost every time.

Conditions must be `bool`. A number is not truthy in Rust, and neither is an empty string.

Using a number as a condition

fn main() {
    let count = 3;
    if count { // error[E0308]
        println!("non-zero");
    }
}

error[E0308]: mismatched types: expected `bool`, found integer

Compare explicitly: `if count != 0 {`. Rust has no truthiness, so every condition says exactly what it tests.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust