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.
for _, v := range values { if v < 0 { break // leaves the for loop } } outer: for { // labeled statement for { break outer // leaves both loops } }
Try it
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.
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
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
switchorselect, a plainbreakleaves that statement, not an enclosing loop. This is the most common mistake: abreakin acasemeant to stop the loop only exits the switch. - No fall-through to worry about. Go cases do not fall through, so you rarely need
breakinside acase. It is only useful to leave a case early, for example after anif. - 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
gotofor that). - Goroutines and closures.
breakcannot leave a function literal. Abreakinside a closure refers only to statements inside that closure. - Range-over-func loops. In a
for ... rangeover an iterator function,breakmakes theyieldcall returnfalse, and the iterator must then stop. Seerange. returnversusbreak.breakcontinues after the loop in the same function;returnleaves the whole function.- Related statements. Use
continueto skip to the next iteration instead of leaving.