Block Scope

Go is block-scoped, meaning variables declared inside a block (defined by curly braces {}) are only accessible within that block and its nested children.

Scoping Levels

  1. Package Scope: Variables declared outside of any function are accessible to the entire package.
  2. Function Scope: Variables declared inside a function.
  3. Block Scope: Variables declared inside loops, if statements, or even explicit blocks.
func main() {
    age := 25 // Function scope
    
    if age > 18 {
        canVote := true // Block scope
        fmt.Println(canVote)
    }
    
    // fmt.Println(canVote) // FAIL: canVote is out of scope
}

Explicit Blocks

Occasionally, you’ll see a plain block used just to isolate variables:

func main() {
    {
        temp := "I only exist here"
        fmt.Println(temp)
    }
    // temp is gone now
}