🎓 A1Learner
🔍

Rust Break & Continue

break and continue are two words that control a loop from inside. break stops the loop completely.

break stops a loop at once

This loop was ready to count to 9, but break ends it the moment n reaches 3:

for n in 0..10 { if n == 3 { break; } println!("{}", n); }

break stops a loop early

This loop could count to 10, but break leaves it as soon as the counter reaches 3:

let mut n = 1;
while n <= 10 {
    if n == 3 {
        break;
    }
    println!("n = {}", n);
    n += 1;
}
println!("stopped");

continue skips one round

Here continue jumps over the printing for 3 only — the loop itself carries on:

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

break can hand back a value

A loop is an expression too: break with a value makes that value the result of the whole loop:

let mut n = 0;
let found = loop {
    n += 1;
    if n == 4 { break n * 10; }
};
println!("found = {}", found);

A label names the outer loop

Write the label just before the outer loop, with a single quote. break with that label leaves both loops at once — count the rounds it skips:

let mut hits = 0;
'outer: for i in 1..=3 {
    for j in 1..=3 {
        if i * j == 4 { break 'outer; }
        hits += 1;
    }
}
println!("hits = {}", hits);

Example

fn main() {
    let mut found = 0;
    'outer: for i in 1..=3 {
        for j in 1..=3 {
            if i * j == 4 { found = i * 10 + j; break 'outer; }
        }
    }
    println!("found code = {}", found);
}

Key points

  • Labels work on loop, while, and for

In this example, two loops are nested. i goes from 1 to 3. Inside it, j goes from 1 to 3. The code looks for i * j == 4. When i is 2 and j is 2, the product is 4. The code saves 2 * 10 + 2 = 22 in found. Then break 'outer stops both loops at once, not just the inner one. The println! shows found code = 22.

Note

Many languages need an extra true/false flag variable to escape nested loops.

A Rust label does the job directly.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How do you break out of an outer loop from inside a nested loop?