Rust Loops Loop Control

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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 <>.



Got any Rust Question?