Control Flow: if, loop, while, and for

Updated

October 31, 2026

Control Flow: if, loop, while, and for

Control flow constructs in Rust are expressions that can return values.

if as an Expression

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };
    println!("Number: {}", number);
}

Loops: loop, while, and for

fn main() {
    // 1. loop with value return
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2;
        }
    };
    println!("Loop result: {}", result);

    // 2. while loop
    let mut n = 3;
    while n > 0 {
        println!("{}!", n);
        n -= 1;
    }

    // 3. for loop over iterators
    for item in 0..3 {
        println!("Index: {}", item);
    }
}