How to Write Loops in Rust

loop, while, and for

Rust uses loop for infinite cycles, while for condition checks, and for to iterate over ranges or collections.

Rust provides three loop constructs: loop for infinite loops, while for condition-based repetition, and for for iterating over ranges or collections.

fn main() {
    // Infinite loop with break
    loop {
        println!("Running...");
        break;
    }

    // Condition-based loop
    let mut count = 0;
    while count < 3 {
        println!("Count: {count}");
        count += 1;
    }

    // Iterating over a range
    for number in 1..=3 {
        println!("Number: {number}");
    }
}