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
- Package Scope: Variables declared outside of any function are accessible to the entire package.
- Function Scope: Variables declared inside a function.
- Block Scope: Variables declared inside loops,
ifstatements, 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
}