go / expert
Snippet
Outer Execution Loop Termination with Labeled Break Statements
Inside a switch statement nested within a for loop, a plain break statement terminates only the inner switch block. Using a labeled break statement target (break StateLoop) explicitly interrupts the outer enclosing loop.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mainimport "fmt"func runFSM(input []int) {StateLoop:for i, v := range input {switch {case v < 0:fmt.Println("Negative encountered, breaking state loop")break StateLoopcase v == 0:continue StateLoopdefault:fmt.Printf("Processing step %d: %d\n", i, v)}}}func main() {runFSM([]int{1, 0, 2, -1, 3})}
Breakdown
1
StateLoop:
Declares a statement label targeting the outer for loop block.
2
switch {
Evaluates conditional branches inside the loop body.
3
break StateLoop
Bypasses default switch break behavior to immediately terminate the labeled outer loop.
4
continue StateLoop
Skips the remainder of the current iteration and advances the labeled outer loop to the next element.