Labelled break
You will not use labelled break or continue every day. Read this once so the syntax is familiar, then come back when nested loops give you a real reason to reach for it.
By default, break and continue act on the innermost enclosing loop. When your loops are nested and you need to break out of an outer one, Go lets you target a specific loop with a labelled statement.
How labels look
A label is an identifier followed by a colon, placed on the line right before the loop it names:
outer:
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
if i*j >= 6 {
fmt.Println("found:", i, j)
break outer
}
}
}
break outer exits the loop labelled outer, not just the inner for j. Without the label, break would leave only the inner loop and the outer one would keep going.
The label name (outer here) is just an identifier; any name works. Convention is to pick something descriptive of what the loop does.
continue with a label
continue can also target a labelled loop. This skips to the next iteration of the outer loop, abandoning the remaining inner work:
outer:
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
if j == 2 {
continue outer // jump to next i, abandon this j loop
}
fmt.Println(i, j)
}
}
// prints: 1 1, 2 1, 3 1
Without the label, continue would skip only to the next j inside the current i.
Labelled break and continue are the right answer for nested loops where you genuinely need to escape more than one level, but they are rare in real Go code. If you find yourself reaching for them often, it usually means the nesting can be restructured: extract the inner loop into a helper function that returns early, use a flag variable, or rethink the data. When labelled break IS the right answer, Go lets you say so clearly.
Write a nested loop that finds the first pair (i, j) whose product exceeds 10:
iruns from1to5inclusive.jruns from1to5inclusive.- When you find a pair with
i * j > 10, print it asfmt.Println(i, j)and break out of both loops immediately using a labelledbreak.
The expected output is a single line: the first such pair.
3 4