Loops

Rust has three loop forms — loop, while, and for — and loop is the odd one out: it repeats forever on purpose, and break can hand back a value from it, which the other two can't do.

for: iterating a range or a collection

Rust src/main.rs
fn main() {
    for i in 1..=5 {
        println!("{}", i);
    }
}
Output
1
2
3
4
5

1..=5 is an inclusive range (1 through 5); leaving off the =1..5 — stops before 5. for is also the standard way to walk a collection like a Vec, which you'll use constantly starting in the Vectors & Collections lesson.

while: repeat until a condition fails

Rust src/main.rs
fn main() {
    let mut stock = 100;
    let mut day = 0;

    while stock > 0 {
        stock -= 30;
        day += 1;
    }
    println!("Ran out after day {}", day);
}
Output
Ran out after day 4

loop: repeats forever, break can return a value

Rust src/main.rs
fn main() {
    let mut count = 0;

    let result = loop {
        count += 1;
        if count == 5 {
            break count * 10;
        }
    };
    println!("{}", result);
}
Output
50

loop has no built-in condition at all — it runs until something inside it explicitly breaks. Giving break a value, as in break count * 10;, makes the entire loop expression evaluate to that value, which is why it can be assigned straight into result.

Note: nested loops can get ambiguous about which one a break or continue applies to. Rust lets you label a loop ('outer: loop { ... }) and target it explicitly with break 'outer;, which resolves that ambiguity instead of leaving you to restructure the code around it.