The Analogy: Searching a Multi-Storey Car Park
You drive into a multi-storey car park at nine in the morning. The structure of the search is fixed: for each level, drive along each row. Two nested loops, and every decision you make while driving is one of a small number of moves. A row you have just finished means carry on to the next row. A delivery van blocking the middle of a row means give up on this level entirely and take the ramp up. And an empty space means you are done with the entire building, not just with the row you happen to be in.
That last move is where beginners get hurt. The instinct is to say "found it, stop", and in most languages "stop" is spelled break — but break only ends the row. You take the space, and then the loop dutifully carries on searching the rest of the level, and the rest of the building, because break binds to the nearest enclosing loop and the nearest one is the row. A search that finds the right answer and then keeps searching is not obviously broken in testing; it just does more work than it should, and it will overwrite the answer if the code assigns as it goes.
Go's fix is signs on the ramps. You label the outer loop, and then you say which loop you mean: break level leaves the building, break row leaves the row, continue level abandons this level and starts the next one. The label is written immediately before the for it names, and once you have read a few of them the code reads like the car park: the reader can see from the keyword alone how far control is about to travel.
There is also a fire exit. Go kept goto, which jumps to a label anywhere in the same function, and it kept it deliberately for the handful of places where nothing else fits: generated parsers, tight error unwinding, state machines. You will read it perhaps twice a year. And there is the move that makes most labels unnecessary in the first place, which is to stop driving and let somebody else do the search: make the nested loop its own function and return the space you found. That refactor is the single most common way experienced Go programmers delete a label, and this lesson ends by doing it.
Syntax or Core Structure
One search, three exits. Watch what happens after the inner loop finishes, because that line is what separates a labeled continue from a plain break.
package main
import "fmt"
func main() {
levels := [][]string{
{"full", "van", "free"},
{"full", "full"},
{"full", "free", "free"},
}
search:
for l, rows := range levels {
for r, state := range rows {
switch state {
case "van":
fmt.Printf("level %d row %d blocked, skipping rest of level\n", l, r)
continue search
case "free":
fmt.Printf("level %d row %d free, parking\n", l, r)
break search
}
fmt.Printf("level %d row %d full\n", l, r)
}
fmt.Printf("level %d fully checked\n", l)
}
fmt.Println("done")
}
Output:
level 0 row 0 full
level 0 row 1 blocked, skipping rest of level
level 1 row 0 full
level 1 row 1 full
level 1 fully checked
level 2 row 0 full
level 2 row 1 free, parking
done
Three things in that transcript are worth pinning down. Level 0 never prints fully checked, because continue search jumps straight to the outer loop's next iteration and skips everything after the inner loop; a plain break would have printed it. Level 1 has no special row, so it runs to completion and prints the summary. Level 2 stops at row 1 and break search leaves both loops, which is why there is no level 2 fully checked line and why done follows immediately.
Technical Depth: How Far Does Control Travel?
Every one of these statements answers the same question with a different distance.
| Statement | Where control goes | How far |
|---|---|---|
break | Past the end of the nearest for, switch or select | One construct |
break label | Past the end of the labeled statement | As far as the label |
continue | The post statement of the nearest for | One loop |
continue label | The post statement of the labeled for | As far as the label |
goto label | The label, anywhere in the same function | Anywhere in the function |
return | Out of the function, running deferred calls | Out |
The asymmetry between the first and third rows is the one to memorize. break counts switch and select as things it can leave, but continue does not: it looks only for loops, so a continue inside a switch inside a for goes to the loop's next iteration without any label. That is why the car park example above needed a label on continue but would also have needed one on break even without the switch.
The Rules for Labels
| Rule | Detail |
|---|---|
Placement for break/continue | The label must precede the for, switch or select it names |
continue label | The labeled statement must be a for; labeling a switch and continuing it is a compile error |
| Scope | The whole enclosing function, and labels do not collide with variable names |
| Unused labels | A compile error: label search defined and not used |
| Formatting | gofmt outdents the label one level relative to the statement it labels |
The unused-label error is a small gift. If you delete the break search but leave the label behind, the build fails rather than leaving a misleading sign hanging over a loop that no longer needs one.
You may also label a switch or a select and break out of it from inside a nested one:
outer:
switch a {
case 1:
switch b {
case 2:
break outer // leaves both switches
}
fmt.Println("not reached when a==1 and b==2")
}
This is legal and occasionally useful, but if you find yourself needing it, the nested switch usually wants to be a function.
The break-in-select Bug
This is the most expensive instance of the "nearest construct" rule, and it appears in real production code. select is one of the things break can leave, so a break meant to stop a worker loop stops the select instead and the loop spins forever.
// Broken: this loop never ends.
for {
select {
case job := <-jobs:
process(job)
case <-done:
break // leaves the select, not the for
}
}
// Fixed with a label.
loop:
for {
select {
case job := <-jobs:
process(job)
case <-done:
break loop
}
}
// Fixed with return, when the loop is the function's whole job.
for {
select {
case job := <-jobs:
process(job)
case <-done:
return
}
}
Nothing warns you about the first version. It compiles, go vet is silent, and the symptom is a goroutine at one hundred percent CPU that no test notices. Module 6 revisits this once channels are on the table; for now, learn the shape so you recognize it on sight.
goto
goto jumps to a label in the same function. The restrictions exist so that the compiler can still guarantee every variable is initialized before use.
| Restriction | Consequence |
|---|---|
| Same function only | No jumping between functions, and no jumping out of a deferred call |
| Cannot jump into a block | You cannot enter an if or for body from outside it |
| Cannot jump over an in-scope declaration | goto done fails if a variable is declared between the jump and the label and is still live at it |
| Backward jumps are allowed | Which means goto can build a loop, though for should |
The legitimate uses are narrow: hand-written or generated state machines, and unwinding a long sequence of setup steps to a single cleanup label in code that predates defer being the answer. In application code, reach for a function and return instead.
Two Interactions Worth Knowing
defer is scoped to the function, not to the loop body, so break and continue do not trigger deferred calls. A defer f.Close() inside a loop over a thousand files holds all thousand handles open until the function returns. The fix is to give the body its own function, which is covered properly in the defer lesson.
In a range-over-function loop, added in Go 1.23, break is implemented by the yield function returning false. A well-behaved iterator checks that return value and stops producing; a badly written one ignores it and keeps going, which is why the standard library's iterators all check. You get the same behavior from return and from a labeled break that leaves the range loop.
Real World Example: Searching Sharded Ledgers, Twice
Here is the same search written both ways: once with a labeled break, and once with the refactor that deletes the label. The data is a set of ledger shards, and the job is to find the first row with a given status, scanning shards in a fixed order so the result is reproducible.
package main
import (
"fmt"
"strings"
)
var shards = map[string][]string{
"shard-a": {"tx-1001,ok", "tx-1002,ok"},
"shard-b": {"tx-1003,pending", "tx-1004,ok", "tx-1005,failed"},
"shard-c": {"tx-1006,ok"},
}
// Fixed order, because ranging a map is randomized.
var order = []string{"shard-a", "shard-b", "shard-c"}
// findWithLabel carries its answer out through variables declared above the loop.
func findWithLabel(status string) (string, int, bool) {
var shard string
var line int
found := false
search:
for _, name := range order {
for i, row := range shards[name] {
if _, s, ok := strings.Cut(row, ","); ok && s == status {
shard, line, found = name, i, true
break search
}
}
}
return shard, line, found
}
// findWithReturn needs no label, no accumulator variables and no found flag.
func findWithReturn(status string) (string, int, bool) {
for _, name := range order {
for i, row := range shards[name] {
if _, s, ok := strings.Cut(row, ","); ok && s == status {
return name, i, true
}
}
}
return "", 0, false
}
func main() {
for _, status := range []string{"failed", "pending", "ok", "reversed"} {
a, i, ok := findWithLabel(status)
b, j, ok2 := findWithReturn(status)
fmt.Printf("%-9s -> %-8s line %d found=%-5t identical=%t\n",
status, a, i, ok, a == b && i == j && ok == ok2)
}
}
Output:
failed -> shard-b line 2 found=true identical=true
pending -> shard-b line 0 found=true identical=true
ok -> shard-a line 0 found=true identical=true
reversed -> line 0 found=false identical=true
Both versions agree on all four queries, including the miss, where the labeled version returns the zero values its variables were declared with and the return version returns them explicitly. The interesting difference is above the loop. findWithLabel needs three variables to exist before the search starts, and the line shard, line, found = name, i, true is doing bookkeeping that has nothing to do with the search itself. Every one of those variables is a place a bug can live: assign two of the three and the function returns a half-answer.
findWithReturn has none of that. return name, i, true is the labeled break and the assignment and the exit, all at once, and there is nothing left in scope afterwards to get wrong. This is why labels are genuinely rare in idiomatic Go: the overwhelming majority of labeled breaks exist inside a loop whose only purpose is to find something, and a function that finds something should return it. When you see a label in a code review, the first question to ask is whether the loop wants to be a function.
Labels still earn their place in three situations. When the outer loop must keep doing work after the inner loop stops, so return would abandon it. When continue label is what you need, because there is no return equivalent for "abandon this level, start the next". And when extracting a function would mean passing six locals in and three out, at which point the label is the smaller evil. Notice also that continue label is exactly equivalent to a plain break when the inner loop is the last statement in the outer body, so a labeled continue only carries information when there is code after the inner loop.
Two details in the code are deliberate. Ranging order rather than shards is what makes the output reproducible, because map iteration order is randomized per run and "the first match" is meaningless without a defined order. And strings.Cut returns a boolean saying whether the separator was there at all, so ok && s == status refuses to match a malformed row instead of comparing against an empty string. In production the third return value would be an error describing the malformed row rather than a silent skip; module 7 covers that.
Common Mistakes
- Using
breakto leave nested loops. It leaves the inner one only, and the outer loop carries on searching after you have already found the answer.
- Using
breakinside aselectto end the surrounding loop. It leaves theselect, the loop spins forever, and nothing warns you.
- Using
breakinside aswitchinside a loop for the same reason. Same cause, same fix: label the loop.
- Putting the label in the wrong place. For
breakandcontinuethe label must sit immediately before the statement it names, not somewhere convenient above it.
- Writing
continue labelwhere the label names aswitch. Only aforcan be continued; the compiler rejects the rest.
- Leaving an unused label behind after deleting the jump. It is a compile error, which is a feature, but people waste time on the message instead of just deleting the line.
- Reaching for a flag variable instead of a label.
found := falseplusif found { break }in two loops is the same idea spelled worse, and it drifts out of sync during edits.
- Assuming
breakorcontinueruns deferred calls.deferfires when the function returns, so adefer f.Close()in a loop holds every handle open.
- Using
gotofor control flow thatforalready expresses. Backward jumps are legal, which makes it possible to write a loop nobody can read.
- Ranging a map when "the first match" matters. The order is randomized per run, so the answer changes between runs; range a fixed slice of keys.
Best Practices
- Before writing a label, ask whether the loop should be a function that returns what it found; most labeled breaks disappear under that refactor.
- Label the loop and name the label after what is being scanned, such as
search,rowsorlevels, neverloop1. - Use
continue labelonly when there is code after the inner loop, because otherwise a plainbreaksays the same thing with less machinery. - Never leave a bare
breakinside aselectunless you actually mean to leave only theselect. - Prefer
returnoverbreak labelwhen the loop is the last thing the function does. - Keep the accumulator variables that a labeled break needs as close to the loop as possible, and set all of them in one assignment so a partial update is impossible.
- Reserve
gotofor generated code and hand-rolled state machines, and add a comment saying which. - Wrap loop bodies that acquire resources in their own function so
deferreleases them on each iteration.
Practice Exercises
- The Silent Overrun: Write a nested loop over a grid that finds the first cell matching a condition and uses a plain
break, with a counter that increments on every comparison. Print the counter and the answer, then switch to a labeled break and print again. Report both counts and explain the difference in one sentence.
- Continue Versus Break: Take the car park program and add a line after the inner loop. Run it once with
continue searchand once with a plainbreak, and record which lines differ. Then move the inner loop so it is the last statement in the outer body and show that the two keywords now behave identically.
- Delete the Label: Take
findWithLabeland refactor it intofindWithReturnyourself without looking at the second version. Then extend both so the search also counts how many rows it examined, and state which version was easier to extend and why.
- The Spinning Worker: Write a loop containing a
selectover two channels, one carrying values and one signalling completion, and use a barebreakin the completion case. Confirm the loop does not stop, then fix it twice, once with a label and once withreturn. Write one sentence on why no tool caught the original.