CodeNebula
Go🔧Core Languagebeginner

Labels and goto

Go · Core Language · Run with go run

Explanation

Go supports statement labels used with `break`, `continue`, and `goto`. A labeled `break` or `continue` targets an *outer* loop — the cleanest way to exit a nested loop. `goto` jumps to a label within the same function; it is rarely used but occasionally clarifies error-cleanup paths or generated code.

Real-World Scenario

Searching a 2D grid for a value — once found, a labeled `break Outer` exits both the inner and outer loops at once, avoiding a flag variable checked after every inner iteration.

Quick Snippet

snippet.go
grid := [][]int{{1, 2}, {3, 4}, {5, 6}}
target := 4

Outer:
for i, row := range grid {
    for j, v := range row {
        if v == target {
            fmt.Printf("found at [%d][%d]\n", i, j)
            break Outer // exits BOTH loops
        }
    }
}

// goto — jump to a label in the same function
i := 0
loop:
if i < 3 {
    fmt.Println(i)
    i++
    goto loop
}

Full Example

labels.go
// Compile: go run labels.go
// Output:
//   found 4 at [1][1]
//   goto loop: 0 1 2
package main

import "fmt"

func main() {
	grid := [][]int{{1, 2}, {3, 4}, {5, 6}}
	target := 4

	// Labeled break exits BOTH loops at once
Outer:
	for i, row := range grid {
		for j, v := range row {
			if v == target {
				fmt.Printf("found %d at [%d][%d]\n", v, i, j)
				break Outer
			}
		}
	}

	// goto jumps to a label in the same function
	fmt.Print("goto loop:")
	i := 0
loop:
	if i < 3 {
		fmt.Print(" ", i)
		i++
		goto loop
	}
	fmt.Println()
}
Run command
go run labels.go