Conditions and loops

if as an expression, match, and the three loops: for over a range or iterator, while, and loop with break value.

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗
main.rs
fn main() {
    for n in 1..=5 {
        if n % 2 == 0 {
            println!("{n} even");
        } else if n == 5 {
            println!("{n} last");
        } else {
            println!("{n} odd");
        }
    }

    let mut i = 3;
    while i > 0 {
        i -= 1;
        if i == 1 {
            continue;
        }
        println!("i = {i}");
    }

    for (index, fruit) in ["apple", "pear"].iter().enumerate() {
        println!("{index} {fruit}");
    }

    let day = 6;
    let kind = match day {
        0 | 6 => "weekend",
        1..=5 => "weekday",
        _ => "unknown",
    };
    println!("{kind}");

    let mut n = 0;
    let found = loop {
        n += 7;
        if n % 5 == 0 {
            break n;
        }
    };
    println!("{found}");
}

Output

1 odd
2 even
3 odd
4 even
5 last
i = 2
i = 0
0 apple
1 pear
weekend
35
  • 1..5 stops before 5; 1..=5 includes it.
  • The condition of if must be a bool — if n { } with a number does not compile.
  • match must cover every possible value; _ matches anything that is left.
  • if and match are expressions: let kind = if x > 0 { "pos" } else { "neg" };.