Skip to main content
The goto statement in Go provides an unconditional transfer of control to a designated, named label within the same function. It alters the sequential execution flow by immediately moving the instruction pointer to the target label.

Mechanics and Lexical Rules

  • Function Scope: Labels are strictly function-scoped. A goto statement cannot transfer control across function boundaries.
  • Namespace: Labels exist in their own namespace. A label can share the same identifier as a variable, type, or package without causing a naming collision.
  • Compiler Strictness: Go enforces strict compilation rules regarding labels. Declaring a label without a corresponding control flow statement (goto, break, or continue) targeting it results in a compile-time error (label defined and not used).
  • Case Sensitivity: Label identifiers are case-sensitive and must conform to standard Go identifier rules (starting with a letter or an underscore).

Control Flow Restrictions

Go imposes strict lexical scoping restrictions on where a goto statement can jump to prevent undefined behavior and uninitialized memory access.

1. Bypassing Variable Declarations

A goto statement cannot jump over the declaration of a variable into a scope where that variable is accessible. Doing so results in a compile-time error because the variable would be in scope but uninitialized. Invalid:
Valid:

2. Jumping Into Nested Blocks

A goto statement cannot transfer control from outside a lexical block into the interior of that block. You cannot jump into the body of an if, for, switch, or select statement from the outside. Invalid:
Valid:
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More