Named breaks in for loops in Rust

For LoopBreakRust

For Loop Problem Overview


Is there a way to have nested for loops in Rust and break the outer one from inside the inner one, the way one could do e.g. in Java? I know Rust supports named breaks in loop but I can't seem to find information about the same regarding for.

For Loop Solutions


Solution 1 - For Loop

Yes. It uses the same syntax as lifetimes.

fn main() {
    'outer: for x in 0..5 {
        'inner: for y in 0..5 {
            println!("{},{}", x, y);
            if y == 3 {
                break 'outer;
            }
        }
    }
}

See loop labels documentation and the related section of the reference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArets PaeglisView Question on Stackoverflow
Solution 1 - For LoopLily BallardView Answer on Stackoverflow