Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Keywords and Statements

The break statement

Reference for Go break: leave the innermost for, switch or select, or a labeled outer statement, with examples and the common switch-inside-loop trap.

break ends the execution of the innermost enclosing for, switch or select statement. Control continues with the first statement after that statement. It is the way to stop a loop early once you have what you were looking for.

A break can carry a label, which names an enclosing for, switch or select. That lets you leave an outer statement from inside a nested one. A break that has no enclosing statement to leave is a compile error.

Go
for _, v := range values {
    if v < 0 {
        break // leaves the for loop
    }
}

outer:
for { // labeled statement
    for {
        break outer // leaves both loops
    }
}

Try it

Go Stop at the first match

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.

Go break inside switch inside for

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.

Syntax

Go
BreakStmt = "break" [ Label ] .
Part Description
Label Optional. Must name an enclosing for, switch or select statement in the same function.

Without a label, break leaves the innermost for, switch or select.

Usage notes

  • Switch and select count. Inside a switch or select, a plain break leaves that statement, not an enclosing loop. This is the most common mistake: a break in a case meant to stop the loop only exits the switch.
  • No fall-through to worry about. Go cases do not fall through, so you rarely need break inside a case. It is only useful to leave a case early, for example after an if.
  • Labels. A label must be used, otherwise the compiler reports "label defined and not used". The label has to sit directly before the statement you want to leave, and it only works for enclosing statements, not for jumping elsewhere (use goto for that).
  • Goroutines and closures. break cannot leave a function literal. A break inside a closure refers only to statements inside that closure.
  • Range-over-func loops. In a for ... range over an iterator function, break makes the yield call return false, and the iterator must then stop. See range.
  • return versus break. break continues after the loop in the same function; return leaves the whole function.
  • Related statements. Use continue to skip to the next iteration instead of leaving.