🎓 A1Learner
🔍

Rust While Loops

A while loop is a loop that repeats while a condition stays true. Rust checks the condition before each round.

Repeat while a condition is true

The loop checks the condition, runs the body, then checks again:

let mut fuel = 3;
while fuel > 0 {
    println!("fuel left = {}", fuel);
    fuel -= 1;
}

The check comes first

The condition is checked before each round — so when it starts false, the body runs zero times:

let fuel = 0;
while fuel > 0 {
    println!("this never prints");
}
println!("done");

break leaves at once

break stops the loop on the spot, wherever it sits:

let mut n = 1;
while true {
    if n > 2 {
        break;
    }
    println!("n = {}", n);
    n += 1;
}
println!("out");

continue skips one round

continue jumps straight to the next check. Here the round for 2 prints nothing, but the loop carries on:

let mut n = 0;
while n < 4 {
    n += 1;
    if n == 2 {
        continue;
    }
    println!("n = {}", n);
}

Example

fn main() {
    let mut fuel = 3;
    while fuel > 0 {
        println!("burning, fuel left = {}", fuel);
        fuel -= 1;
    }
    println!("liftoff!");
}

Key points

  • The condition must be a bool
  • Something inside the loop must move the condition toward false, or the loop never ends

In this example, fuel starts at 3. The loop checks: is fuel > 0? Yes, so it prints the fuel level. Then fuel -= 1 makes fuel one smaller. The loop runs again with 2, then with 1. After printing 1, fuel becomes 0. Now the check fails, the loop ends, and the program prints "liftoff!". If you deleted the fuel -= 1 line, fuel would stay 3 forever — the classic endless loop mistake.

Note

When you do know the count in advance, a for loop over a range is clearer and safer.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How many times can a while loop's body run?