Does a break statement break from a switch/select?

Matt picture Matt · Jun 19, 2012 · Viewed 92.8k times · Source

I know that switch/select statements break automatically after every case. I am wondering, in the following code:

for {
    switch sometest() {
    case 0:
        dosomething()
    case 1:
        break
    default:
        dosomethingelse()
    }
}

Does the break statement exit the for loop or just the switch block?

Answer

peterSO picture peterSO · Jun 19, 2012

Break statements, The Go Programming Language Specification.

A "break" statement terminates execution of the innermost "for", "switch" or "select" statement.

BreakStmt = "break" [ Label ] .

If there is a label, it must be that of an enclosing "for", "switch" or "select" statement, and that is the one whose execution terminates (§For statements, §Switch statements, §Select statements).

L:
  for i < n {
      switch i {
      case 5:
          break L
      }
  }

Therefore, the break statement in your example terminates the switch statement, the "innermost" statement.