Rust Loop Control


Example

All looping constructs allow the use of break and continue statements. They affect the immediately surrounding (innermost) loop.

Basic Loop Control

break terminates the loop:

for x in 0..5 {
    if x > 2 { break; }
    println!("{}", x);
}
Output
0
1
2

continue finishes the current iteration early

for x in 0..5 {
    if x < 2 { continue; }
    println!("{}", x);
}
Output
2
3
4

Advanced Loop Control

Now, suppose we have nested loops and want to break out to the outer loop. Then, we can use loop labels to specify which loop a break or continue applies to. In the following example, 'outer is the label given to the outer loop.

'outer: for i in 0..4 {
    for j in i..i+2 {
        println!("{} {}", i, j);
        if i > 1 {
            continue 'outer;
        }
    }
    println!("--");
}
Output
0 0
0 1
--
1 1
1 2
--
2 2
3 3

For i > 1, the inner loop was iterated only once and -- was not printed.


Note: Do not confuse a loop label with a lifetime variable. Lifetime variables only occurs beside an & or as a generic parameter within <>.