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

More Go tasks

Back to the full Go cheat sheet