Labeled Break Exits Nested Loops

Labeled break jumps out of every nesting level and labeled continue restarts the outer loop, replacing flag-checked exits across nested range scans.

GoResilience

Code

gosnippet
44 lines
package main

import "fmt"

func main() {
	grid := [][]int{
		{1, 2, 3},
		{4, 0, 6},
		{7, 8, 9},
	}

	// 无标签:break 只跳出内层,外层继续扫描
	for _, row := range grid {
		for _, v := range row {
			if v == 0 {
				break
			}
			fmt.Print(v, " ")
		}
	}
	fmt.Println()

	// 带标签:break search 一次跳出两层循环
search:
	for i, row := range grid {
		for j, v := range row {
			if v == 0 {
				fmt.Printf("zero at %d,%d\n", i, j)
				break search
			}
		}
	}

	// continue 标签:放弃当前外层本轮,直接进入下一行
skip:
	for i, row := range grid {
		for _, v := range row {
			if v == 0 {
				continue skip
			}
		}
		fmt.Println("row", i, "clean")
	}
}

How it works

Labeled Break Exits Nested Loops is built around the function main.

The loop for _, row := range grid is the only repeated construct.

Putting it to use

The demo output is labeled (zero at, row), so the output doubles as a step-by-step trace of what the file did.

The core lines, annotated

for _, row := range grid {
	for _, v := range row {
		if v == 0 {
			break
		}
		fmt.Print(v, " ")
	}
}
for i, row := range grid {
	for j, v := range row {
		if v == 0 {
			fmt.Printf("zero at %d,%d\n", i, j)
			break search
		}
	}
}
for i, row := range grid {
	for _, v := range row {
		if v == 0 {
			continue skip
		}
	}
	fmt.Println("row", i, "clean")
}

Interactive Tools for This Topic

FAQ

What does Labeled Break Exits Nested Loops print when run?
Running the file directly is enough — expect labeled output lines such as `zero at`, `row`.