go / expert
Snippet
Targeted Multi-Level Control Flow with Labeled Break in Type Switches
In Go, an unlabelled break inside a switch statement only terminates the switch itself, not an enclosing for loop. Attaching a label to the outer loop allows a break statement nested within a type switch to immediately terminate the outer iteration.
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 processItems(items []any) {OuterLoop:for _, item := range items {switch v := item.(type) {case int:if v < 0 {fmt.Println("Encountered negative int, breaking outer loop")break OuterLoop}case string:fmt.Println("String:", v)}}}func main() {processItems([]any{"hello", -5, "world"})}
Breakdown
1
OuterLoop:
Attaches a statement label to the enclosing for loop for precise jump control.
2
break OuterLoop
Terminates execution of the labeled outer for loop rather than just breaking out of the type switch block.