Labeled Break And Continue Nested Loops

Rust labels live in the loop-type position ('search: for …) so break 'search unwinds every nesting level at once and continue 'rows discards one outer round.

RustResilience

Code

rustsnippet
34 lines
fn main() {
    let grid = [[1, 2, 3], [4, 0, 6], [7, 8, 9]];

    // 无标签:break 只退出内层循环
    for row in &grid {
        for v in row {
            if *v == 0 {
                break;
            }
            print!("{v} ");
        }
    }
    println!();

    // labeled break:一次跳出两层嵌套循环
    'search: for (i, row) in grid.iter().enumerate() {
        for (j, v) in row.iter().enumerate() {
            if *v == 0 {
                println!("zero at {i},{j}");
                break 'search;
            }
        }
    }

    // labeled continue:放弃当前外层本轮,直接进入下一行
    'rows: for (i, row) in grid.iter().enumerate() {
        for v in row {
            if *v == 0 {
                continue 'rows;
            }
        }
        println!("row {i} clean");
    }
}

What the code does

Labeled Break And Continue Nested Loops keeps everything in the function main.

Repetition is confined to for row in &grid — the rest of the file is straight-line.

Using it

The demo output is labeled (zero at, row), so every printed line maps back to its originating operation.

Key statements

'search: for (i, row) in grid.iter().enumerate() {
    for (j, v) in row.iter().enumerate() {
        if *v == 0 {
            println!("zero at {i},{j}");
            break 'search;
        }
    }
}
'rows: for (i, row) in grid.iter().enumerate() {
    for v in row {
        if *v == 0 {
            continue 'rows;
        }
    }
    println!("row {i} clean");
}

Interactive Tools for This Topic

FAQ

What does Labeled Break And Continue Nested Loops print when run?
Run it as a complete program — the output lines carry labels such as `zero at`, `row`.