Rust While Loops

Rust offers two open-ended looping constructs: while for condition-checked repetition, and loop for an intentionally infinite loop that you break out of manually.

The while Loop

A while loop evaluates its boolean condition before every iteration, including the very first one, and keeps running its body for as long as that condition stays true.

A simple countdown

fn main() {
    let mut countdown = 5;

    while countdown > 0 {
        println!("{}...", countdown);
        countdown -= 1;
    }

    println!("Liftoff!");
}

The loop Keyword

loop repeats its block forever until it hits an explicit break. It's the right tool when you don't know the exit condition ahead of time, and unlike while, break can carry a value out of a loop so the whole loop can be used as an expression.

loop with break returning a value

fn main() {
    let mut attempts = 0;

    let result = loop {
        attempts += 1;
        if attempts == 3 {
            break attempts * 10;
        }
    };

    println!("Succeeded after {} attempts, result = {}", attempts, result);
}
Note: break value works only with loop, not while or for, because those two aren't guaranteed to run their body at all — there would be no sensible value to produce if the condition were false from the start.

Labeled Loops

Labeled break in nested loops

fn main() {
    let mut x = 0;

    'outer: while x < 5 {
        let mut y = 0;
        while y < 5 {
            if x * y > 6 {
                println!("breaking outer at x={}, y={}", x, y);
                break 'outer;
            }
            y += 1;
        }
        x += 1;
    }
}
ConstructChecks a condition first?Can return a value via break?Typical use
whileYesNoRepeat while a condition holds
loopNo — infinite by defaultYesRepeat until you decide to stop, possibly returning a computed value
Note: Forgetting to update the loop variable inside a while loop — for example, leaving out countdown -= 1 — is a common cause of infinite loops. The compiler cannot catch this for you, since it depends entirely on runtime logic.
  • while checks its condition before every iteration, including the first.
  • loop has no condition at all and only stops via break (or a process exit).
  • break can carry a value out of loop, letting the whole loop act as an expression.
  • Label loops with 'name: so break or continue inside nested loops can target a specific outer loop.

Exercise: Rust While Loops

When does a `while` loop check its condition?