skip to content

In a Rust nested grid search, what do `break 'rows` and `continue 'rows` do, and when would you use a labeled block instead?

level: middleimportance: should knowfreq 45%

answer

  1. a lifetime-like name before the loop
  2. outer loop, not innermost
  3. exit versus next iteration
  4. labeled block, Rust 1.65

basics

~20 s

A label such as 'rows: names an enclosing loop: break 'rows leaves it from any depth and continue 'rows starts its next iteration. Since Rust 1.65 a labeled block, 'check: { ... }, can be left early with break 'check value without being a loop.

solid answer

~50 s

Unlabeled `break` and `continue` act on the innermost loop. Putting a label in front of an outer loop, `'rows: for (r, row) in grid.iter().enumerate()`, lets code in an inner loop say which loop it means: `break 'rows` ends the outer loop and both loops stop, while `continue 'rows` abandons the rest of the current row and moves to the next one. A labeled `loop` can also carry a value out, `break 'search Some((r, c))`; a labeled `for` cannot, because it evaluates to `()`. Since Rust 1.65 a plain block can be labeled too: `let verdict = 'check: { ... break 'check "missing"; ... "ok" };` gives early exits with a value and no loop. Inside a labeled block, a `break` must name a label (an unlabeled one inside a loop is E0695) and `continue` cannot target the block (E0696).

code

rust · 24 lines
rust
fn find_seat(grid: &[Vec<char>], want: char) -> Option<(usize, usize)> {
    let mut found = None;
    'rows: for (r, row) in grid.iter().enumerate() {
        for (c, &cell) in row.iter().enumerate() {
            if cell == '#' {
                continue 'rows; // a wall ends this row: skip to the next row
            }
            if cell == want {
                found = Some((r, c));
                break 'rows; // stop both loops at the first match
            }
        }
    }
    found
}

fn main() {
    let grid = vec![
        vec!['.', '#', 'S'],
        vec!['.', '.', 'S'],
        vec!['S', '.', '.'],
    ];
    println!("{:?}", find_seat(&grid, 'S'));
}

go deeper

for a junior

Know that plain break and continue act on the innermost loop and that a 'label lets you target an outer one.

for a middle

Contrast break 'rows with continue 'rows in a nested search, and show a labeled loop carrying a value out with break 'search value.

for a senior

Use labeled blocks (Rust 1.65) for early exits with values, and know E0695, E0696 and why labels cannot cross a closure (E0767).

for a principal

Decide when nesting deserves a named helper with return instead of labels, keeping control flow reviewable as functions grow.

## Labels name loops A **loop label** is written like a lifetime, a quote followed by an identifier and a colon, in front of a loop: `'rows: for ...`, `'retry: loop { ... }`, `'poll: while ...`. On its own it does nothing. It matters when code inside nested loops needs to say *which* loop a `break` or `continue` refers to; without a label, both act on the **innermost** enclosing loop. ## What labeled `break` and `continue` do | Statement | Effect | |---|---| | `break` | ends the innermost loop | | `break 'rows` | ends the loop labeled `'rows`, and every loop nested inside it | | `continue` | starts the next iteration of the innermost loop | | `continue 'rows` | abandons the inner loops and starts the next iteration of `'rows` | | `break 'search value` | ends the labeled `loop` (or labeled block) with `value` as its result | In a grid search the two forms do different jobs. `continue 'rows` says "this row is finished, go to the next row", for example when a wall cell makes the rest of the row unreachable. `break 'rows` says "the search is over", for example at the first matching cell. Without labels the usual workaround is a `found` flag checked after the inner loop, which is easy to get wrong. ## Carrying a value out of nested loops `break 'label value` works only when the labeled construct can have a value, which means a `loop` or a labeled block. One pattern wraps the nested `for` loops in a labeled `loop` that runs once: - the inner loops `break 'search Some((r, c))` on a hit; - after the `for` loops, `break 'search None` ends the outer `loop` with the miss. A labeled `for` or `while` still evaluates to `()`, so `break 'rows (r, c)` on a `for` is E0571. Extracting the search into a function and using `return Some((r, c))`, or using an iterator method, are the other common answers; the iterators material covers the second. ## Labeled blocks (Rust 1.65) Rust 1.65 stabilised **breaking from labeled blocks**. A labeled block runs once, like an ordinary block, but code inside it may leave early with `break 'label value`. Its value is the common type of every `break` operand and its final expression. This gives early exits in the middle of a computation without a loop, a closure or a helper function. The Reference adds rules that rustc enforces: 1. **Every `break` inside a labeled block must carry a label.** An unlabeled `break` inside `'a: { ... }` nested in a loop is **E0695**, *unlabeled `break` inside of a labeled block*, because a reader could not tell whether it leaves the block or the loop. 2. **A labeled block cannot be continued.** `continue 'b` aimed at a block is **E0696**, *`continue` pointing to a labeled block*. 3. **The block must start with its label**; an ordinary unlabeled block can never be the target of a `break`. ## Rules worth knowing - **Labels are hygienic and scoped like local variables.** An inner loop may reuse an outer label's name; rustc warns that the *label name `'a` shadows a label name that is already in scope*, and `break 'a` then refers to the inner one. - **An unused label triggers the `unused_labels` warning**, part of the `unused` group. - **Labels do not cross closures, functions or async blocks.** `break 'a` inside a closure defined in `'a: loop` is **E0767**, *use of unreachable label*. Return a value from the closure and break outside it. - **`'_` is not a valid label.** - **Labels are local syntax, not `goto`**: you can only exit or restart an enclosing construct, never jump into one or sideways. ## Tracing the grid example In the first snippet below the grid has a wall in row 0 before an `S`: 1. Row 0, column 0 is `.`, so the inner loop moves on. 2. Row 0, column 1 is `#`, so `continue 'rows` abandons row 0; the `S` at column 2 is never examined. 3. Row 1 has no wall before its `S` at column 2, so `found` becomes `Some((1, 2))` and `break 'rows` ends both loops; row 2 is never visited. When the nesting grows past two levels, consider a helper function: `return` from it reads as clearly as a labeled `break`, and the function gets a name and a test of its own.

  • Why does rustc reject `loop { 'a: { if done { break; } } }`?
    Inside a labeled block every `break` must name a label, so the unlabeled one is E0695, *unlabeled `break` inside of a labeled block*. rustc refuses to guess whether it means the block or the loop. Write `break 'a` to leave the block, or label the loop and break that label.
  • Can a closure defined inside a labeled Rust loop break out of that loop?
    No. Labels are not reachable through closures, functions or async blocks, so `break 'a` inside the closure is E0767, *use of unreachable label*. Have the closure return a value, such as a `bool` or an `Option`, and break with the label outside it.
  • In Rust, when is a labeled block better than a helper function?
    When the early exits need several local variables and the logic is short: a labeled block keeps everything in scope without passing arguments. Once the block grows or deserves its own name and test, a function with `return` usually reads better.

A label is like a name painted on one floor of a building: a plain break leaves the room you are in, while break 'rows takes the exit off the named floor, however many rooms deep you are.

  • continue 'rows only skips the current cell of the inner loop
  • a labeled for loop can return a value with break 'label value
  • labels let you jump anywhere in a function, like goto
  • a break inside a closure can exit the loop that encloses the closure
  • labeled blocks have existed since Rust 1.0 alongside labeled loops

Assumes Rust 1.99 on edition 2024; labeled loops have been stable since 1.0, breaking from labeled blocks since Rust 1.65.