0 day streak
go / expert
Snippet

Labeled Break to Exit Nested Loops Cleanly

Go has no multi-level break by default — a plain break only exits the innermost loop or switch. A statement label placed before the outer for converts it into a target: break Outer transfers control immediately past that loop, skipping any remaining iterations of both dimensions. The same mechanic works with continue Label to skip to the next outer iteration. It is the idiomatic alternative to flag variables or extracting the inner block into a helper purely for an early return.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
import "fmt"
func findPair(rows [][]int, target int) (int, int, bool) {
ri, ci := -1, -1
found := false
Outer:
for i, row := range rows {
for j, v := range row {
if v == target {
ri, ci, found = i, j, true
break Outer
}
}
}
return ri, ci, found
}
func main() {
m := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
r, c, ok := findPair(m, 5)
fmt.Printf("found=%v at %d,%d\n", ok, r, c)
}
Breakdown
1
Outer:
A statement label — any identifier followed by a colon. It names the immediately following for so break and continue can target it.
2
for i, row := range rows {
The outer loop iterates rows; without the label, an inner break would only stop the inner-column scan.
3
break Outer
Transfers control past the labeled for in one step. Both loops terminate; the captured ri, ci survive.
4
return ri, ci, found
The found bool disambiguates a real (0,0) hit from the sentinel (-1,-1) — a small but important contract detail.