Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
goto LabelName

// ... intermediate code ...

LabelName:
    // execution continues here

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:
func invalidDeclarationJump() {
    goto Target // Compile error: goto Target jumps over declaration of val
    
    val := 42 
    
Target:
    fmt.Println(val) 
}
Valid:
func validDeclarationJump() {
    var val int
    goto Target 
    
    val = 42 
    
Target:
    fmt.Println(val) // Valid: declaration was not bypassed, only assignment
}

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:
func invalidBlockJump() {
    goto InnerBlock // Compile error: goto InnerBlock jumps into block
    
    if true {
    InnerBlock:
        fmt.Println("Inside conditional block")
    }
}
Valid:
func validBlockJump() {
    if true {
        goto OuterBlock 
    }
    
OuterBlock:
    fmt.Println("Outside conditional block")
}
Master Go with Deep Grasping Methodology!Learn More