Closures in Go
From the Go cheat sheet ยท Functions ยท verified Jul 2026
Closures
Anonymous functions and closures
go
// Anonymous function
greet := func(name string) string {
return "Hello, " + name
}
fmt.Println(greet("Go"))
// Closure captures variables
counter := func() func() int {
n := 0
return func() int {
n++
return n
}
}()
fmt.Println(counter()) // 1
fmt.Println(counter()) // 2๐ Closures capture variables by reference, not by value
๐ก Common for goroutines, callbacks, and factory functions
๐ Go 1.22+ fixed the loop variable capture bug
โก Functions are first-class values in Go