Break statements
A “break” statement terminates execution of the innermost “for”, “switch”, or “select” statement within the same function.
BreakStmt = "break" [ Label ] .
We’ll discuss the Label
mentioned tomorrow. Until then, the key word here is innermost. This shouldn’t be very surprising to anyone familiar with other programming languages. But despite its familiarity, I’ve been bitten more than once by forgetting this key detail.
It’s perhaps easiet to forget when you have, say, a switch
statement within a for
loop, for example. I find it’s easy to forget about nested statements when they’re of different types like this.
var capacity = 10
for _, widget := range allWidgets {
switch widget.Size {
case "small":
capacity -= 1
case "medium":
capacity -= 3
case "large":
if widget.Fragile {
fmt.Println("we can't handle large fragile widgets")
break // This breaks out of the switch statement, not the for loop
}
capacity -= 5
}
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)