TExcelTAD
Home › Rust › Rust Loops

Rust Loops

Programs often need to repeat work: process every line of a file, retry a task until it succeeds, or count down to zero. Rust gives you three looping keywords, each suited to a different situation.

Keyword Runs… Typical use
loop forever, until you break retrying, game loops, "search until found"
while as long as a condition is true counting, waiting for a state to change
for once for each item in a range or collection walking through numbers, arrays, vectors

This chapter covers loop. The next two chapters look at while and for in detail.

The loop keyword

loop repeats its body with no built-in stopping condition. You decide when to leave by using break.

rust · try it yourself
fn main() {
    let mut energy = 3;

    loop {
        println!("Running... energy left: {}", energy);
        energy -= 1;

        if energy == 0 {
            println!("Out of energy, stopping.");
            break;
        }
    }
}
Running... energy left: 3
Running... energy left: 2
Running... energy left: 1
Out of energy, stopping.

Without the break, this program would never finish. That is sometimes exactly what you want — a server waiting for requests runs "forever" — but most loops in beginner programs should have a clear exit.

Returning a value from loop

In Rust, loop is an expression: it can produce a value. Put the value after break, and the whole loop evaluates to it. This is handy when you are searching for something.

rust · try it yourself
fn main() {
    let mut n = 1;

    // Find the first number whose square is greater than 50
    let answer = loop {
        if n * n > 50 {
            break n;
        }
        n += 1;
    };

    println!("First number with square > 50: {}", answer);
    println!("Its square is {}", answer * answer);
}
First number with square > 50: 8
Its square is 64

Notice the semicolon after the closing } of the loop: let answer = loop { ... }; is a normal let statement.

Note: Only loop can return a value with break value. A while or for loop always evaluates to () (the empty "unit" value), because the compiler cannot be sure the body runs at all.

Skipping an iteration with continue

continue jumps straight back to the top of the loop, skipping the rest of the current pass. Use it to ignore items you are not interested in.

rust · try it yourself
fn main() {
    let mut i = 0;

    loop {
        i += 1;
        if i > 10 {
            break;
        }
        if i % 3 != 0 {
            continue; // not a multiple of 3, skip it
        }
        println!("{} is a multiple of 3", i);
    }
}
3 is a multiple of 3
6 is a multiple of 3
9 is a multiple of 3

Loop labels

When loops are nested, break and continue apply to the innermost loop. To control an outer loop, give it a label: a name that starts with a single quote, such as 'outer.

rust · try it yourself
fn main() {
    let mut row = 0;

    'outer: loop {
        row += 1;
        let mut col = 0;

        loop {
            col += 1;
            if col > 3 {
                break; // leaves the inner loop only
            }
            if row * col == 6 {
                println!("Found 6 at row {}, col {}", row, col);
                break 'outer; // leaves both loops
            }
            println!("row {} col {} -> {}", row, col, row * col);
        }
    }

    println!("Done.");
}
row 1 col 1 -> 1
row 1 col 2 -> 2
row 1 col 3 -> 3
row 2 col 1 -> 2
row 2 col 2 -> 4
Found 6 at row 2, col 3
Done.

Labels also work with continue 'outer, and with while and for loops.

Choosing the right loop

  • Use for when you know what you are iterating over (a range like 1..=10, an array, a vector). It is the most common loop in Rust code and cannot go out of bounds.
  • Use while when you keep going until some condition changes.
  • Use loop when the exit point is in the middle of the body, or when you need the loop to return a value.

Tip: If you find yourself writing loop { if !condition { break; } ... }, a while condition { ... } loop says the same thing more clearly.

Test yourself

How do you stop a loop that has no condition?

  1. Use stop
  2. Use break
  3. Use return false
  4. It stops automatically after 100 iterations

What does let x = loop { break 5; }; store in x?

  1. ()
  2. true
  3. 5
  4. It does not compile

In nested loops, what does break 'outer; do?

  1. Breaks only the inner loop
  2. Breaks the loop labelled 'outer
  3. Restarts the outer loop
  4. Exits the program