RRust By Example
intermediateFlow Control

Labeled Loops

Use labels with break and continue for nested loops.

Labeled Loops

Use labels with break and continue for nested loops.

Difficulty

Intermediate

Code

rust
fn main() {
    'outer: for i in 0..5 {
        for j in 0..5 {
            if i + j > 4 {
                println!("breaking at i={}, j={}", i, j);
                break 'outer;
            }
            println!("({}, {})", i, j);
        }
    }

    // labeled loop with return value
    let result = 'search: loop {
        for i in 0..10 {
            if i * i > 50 {
                break 'search i;
            }
        }
    };
    println!("first i where i*i > 50: {}", result);
}

Explanation

Labels let you break/continue specific nested loops.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the flow-control category to build a complete understanding of this topic.

More Flow Control Examples