Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 147 ยท Operators and Control Flow

Labels, break, continue and goto

Learn how Go labels let break and continue control nested loops, switch and select, and when the rarely used goto statement is acceptable, including its compile-time restrictions.

A plain break or continue only affects the innermost loop. When you have loops inside loops, or a switch inside a for, you often want to leave or restart an outer statement from deep inside. Go solves this with labels: you put a name in front of a statement, and break or continue can refer to that name.

This lesson shows how to use labeled break and continue, how labels interact with switch and select, and where Go's goto fits. Spoiler: you will use labels now and then, and goto almost never. If you need a refresher on the basic forms, see for Loops and switch.

Label syntax

A label is an identifier followed by a colon, placed before a statement:

Go
outer:
	for i := 0; i < 3; i++ {
		...
	}

By convention gofmt places a label one indent level to the left of the statement it labels, as shown above (and in the examples below). Labels live in their own namespace: a label can have the same name as a variable without conflict, though that would be confusing. A label is scoped to the function that contains it.

break label and continue label may only name a label on an enclosing for, switch or select statement (continue only for for loops, since only loops can continue).

Labeled break: leaving nested loops

A classic case is searching a two-dimensional grid. After you find the item you want to leave both loops, but a plain break only leaves the inner one.

Go Searching a grid with a labeled break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Without the label you would need a boolean flag that the outer loop checks, or you would move the search into its own function and return from it. Both are good alternatives: extracting a function is often the cleanest option, and return works from any depth. Use a label when the loops are short and the logic reads clearly.

Labeled continue: next iteration of an outer loop

continue outer abandons the current iteration of the inner loop and the rest of the outer body, and goes straight to the next iteration of the outer loop. It is perfect for "try each candidate; skip it as soon as one test fails":

Go Listing primes with continue outer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If the inner loop finishes without finding a divisor, control reaches primes = append(...). If it finds one, continue next skips the append entirely. The result is [2 3 5 7 11 13 17 19 23 29].

Labels with switch and select

Remember from the switch lesson that break inside a switch or select leaves only that statement. When the switch sits inside a loop that you want to end, label the loop.

Go A command loop that ends from inside a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice what happens for reset: continue loop skips the fmt.Println("after ...") at the bottom of the loop body, so that line is missing from the output. Also notice that add 100 never runs, because break loop ended the whole loop at quit.

The same technique is common with select in goroutines that wait on several channels: a for { select { ... } } loop is ended with break loop (or a return). Buffered Channels and select shows it in action.

Labels must be used

Go refuses to compile a label that is never used, just as it refuses unused variables and imports. That keeps leftover labels from piling up.

Go An unused label (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler says:

TEXT
./main.go:6:1: label unused defined and not used

goto

goto label jumps to a labeled statement in the same function. Go keeps it, but with restrictions that make it much safer than in C:

  1. It cannot jump over a variable declaration that is in scope at the label. Otherwise the jump could land after a variable that was never initialized.
  2. It cannot jump into a block (such as the body of an if or for) from outside it. You can jump out of a block.
Go goto jumping over a declaration (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is:

TEXT
./main.go:6:7: goto done jumps over declaration of x at ./main.go:7:4

Here is a legal and fairly typical use. A retry loop written with goto makes the control flow explicit, although a for loop with continue would do just as well in this simple case:

Go A retry written with goto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When is goto acceptable?

Honestly, very rarely. In day-to-day Go you replace goto with a loop, a function, or defer for cleanup (see defer). You will mainly meet it in:

  • Generated code and parsers or state machines, where jumping between states is the natural model.
  • Low-level code in the standard library, such as error cleanup paths in older, performance-sensitive functions.

If you find yourself writing goto in application code, try a loop with continue, an early return, or a helper function first. These alternatives are almost always easier to read.

Because goto cannot jump over declarations, you often see all variables declared at the top of a function that uses it. That is a sign the function is probably doing too much and should be split.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In for { switch x { case 1: break } }, what does break do?

    break always applies to the innermost for, switch or select. To end the loop you need a label.
  2. 2. What does continue outer do inside an inner loop?

    The inner loop and the rest of the outer body are abandoned, and the labeled loop proceeds with its next iteration (running its post statement).
  3. 3. What happens if you declare a label and never use it?

    Go rejects unused labels, just like unused variables and imports.
  4. 4. Which goto is rejected by the compiler?

    A goto may not skip a variable declaration that is still in scope at the label.
  5. 5. Which label placement is valid for break lbl?

    break can only name a label attached to an enclosing for, switch or select statement; continue only a label on an enclosing for loop.

Summary

  • A label is name: before a statement. break name and continue name act on an enclosing labeled statement.
  • Use break label to leave nested loops or to end a loop from inside a switch or select; use continue label to start the next iteration of an outer loop.
  • Unused labels are compile errors.
  • goto jumps within a function, but not over variable declarations and not into blocks.
  • Prefer loops, early returns, helper functions and defer to goto in everyday code.

Next: Functions