Does a Looping Interfere with Break in Switch?
In Go programming, break statements are designed to terminate the innermost execution of either a for, switch, or select statement. While switch statements typically break automatically after each case, the question arises:
Does a break statement within a switch block in a for loop break out of the loop or solely the switch block?
To clarify this, let's refer to the official Go Programming Language Specification:
BreakStmt = "break" [ Label ] .
Here, if a label is present, it should correspond to an enclosing for, switch, or select statement. Breaking this labeled statement will terminate the specified statement's execution.
L: for i < n { switch i { case 5: break L // Break for loop L } }
In the given example, the break statement breaks the switch statement, which is considered the innermost statement. Therefore, the break statement does not exit the for loop. It only terminates the execution of the switch block.
The above is the detailed content of Does `break` Exit a `for` Loop When Used Inside a `switch` Statement in Go?. For more information, please follow other related articles on the PHP Chinese website!