Go🔧Core Languagebeginner
Closures
Go · Core Language · Run with go run
Explanation
A closure is a function that captures variables from its enclosing scope by reference. In Go, closures are commonly used to create stateful function values, implement middleware, and build iterators. Since Go 1.22, range loop variables create fresh bindings per iteration, eliminating the classic closure-in-loop pitfall.
Real-World Scenario
A counter factory returns a closure that increments an internal counter each time it's called — useful for generating unique IDs in a request handler without shared global state.
Quick Snippet
snippet.go
func makeCounter() func() int {
n := 0
return func() int {
n++
return n
}
}
c := makeCounter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
fmt.Println(c()) // 3
// Each counter has independent state
d := makeCounter()
fmt.Println(d()) // 1Full Example
closures.go
// Compile: go run closures.go
// Output:
// c: 1 2 3
// d: 1
package main
import "fmt"
func makeCounter() func() int {
n := 0
return func() int {
n++
return n
}
}
func main() {
c := makeCounter()
fmt.Println("c:", c(), c(), c())
// Independent state per closure
d := makeCounter()
fmt.Println("d:", d())
}
Run command
go run closures.go