Does a break Statement Break from a Switch/Select or Escape the Loop It Resides in?
Many programming languages employ the switch/select statement to handle multiple cases, typically breaking automatically after each case execution. However, in Go, does a break statement within a switch/select statement solely terminate the switch/select block or cause an exit from the enclosing loop?
Answer:
In Go, a break statement exits the innermost for, switch, or select statement. If a label is provided, it must match the label of the enclosing loop, switch, or select construct.
The following excerpt from The Go Programming Language Specification clarifies this behavior:
Break statements, The Go Programming Language Specification. A "break" statement terminates execution of the innermost "for", "switch" or "select" statement. BreakStmt = "break" [ Label ] .
Therefore, in the provided example:
for { switch sometest() { case 0: dosomething() case 1: break default: dosomethingelse() } }
The break statement terminates only the switch statement, not the enclosing for loop.
The above is the detailed content of Does `break` Exit a `switch/select` or its Enclosing Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!