Skip to main content
A labeled statement in Go is an identifier followed by a colon (:) that precedes a statement, serving as an explicit execution target for goto, break, and continue control flow operations.

Syntax

A label can also be declared on its own line, implicitly attaching to the immediately following statement or acting as an empty statement target at the end of a block.

Scope and Namespace

  • Function Scope: Labels are scoped to the function in which they are declared. They are not block-scoped. A label declared anywhere in a function is visible throughout the entire function, but cannot be referenced from nested functions, closures, or outside the function.
  • Independent Namespace: Labels exist in a separate namespace from variables, types, and functions. A label can share an identifier with a variable without causing a shadowing conflict or compilation error.
  • Strict Utilization: Go enforces strict label utilization. Declaring a label without subsequently referencing it with a goto, break, or continue statement results in a compile-time error (label X defined and not used).

Control Flow Mechanics

Labels modify the default behavior of three specific control flow statements:

1. break

When break is followed by a label, it terminates the execution of the specific for, switch, or select statement associated with that label, rather than just the innermost enclosing block.

2. continue

When continue is followed by a label, it skips the remaining execution of the current iteration and advances to the next iteration of the specific for loop associated with that label. The label must be attached directly to a for statement.

3. goto

The goto statement transfers control unconditionally to the corresponding labeled statement within the same function. Go imposes strict lexical restrictions on goto jumps to prevent invalid program states:
  • A goto statement must not cause any variables to come into scope that were not already in scope at the point of the goto.
  • A goto cannot jump into a nested block from outside that block.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More