Closures
A closure is a function literal that refers to variables from the enclosing function. Those variables stay alive as long as the closure does, and assignments inside the closure change the original variables.
Detailed Explanation
You write func() { n++ } inside another function. n is not a parameter and not a global. The inner function closes over n. Each time you call the inner function, it sees the current n, not a snapshot from when you wrote the literal. That is the difference between a closure and a function that only uses its arguments.
Capture is by variable, not by value. The closure holds a reference to n. Two closures that mention the same n share it. defer func() { fmt.Println(err) }() prints the err at exit, which is why this form is the fix for defer fmt.Println(err) freezing a nil. If you want a snapshot, pass the value as a parameter: func(err error) { fmt.Println(err) }(err).
Loop variables. Since Go 1.22, each iteration of for i := range s has its own i, so go func() { fmt.Println(i) }() in the loop body is safe. On older language versions the goroutines all printed the final i. Passing i as an argument is still the clearest form when the code must run on mixed toolchains.
Methods and bound receivers are not closures, but a method value s.Append is a function that holds s. Changing s later may or may not be visible depending on whether the receiver is a pointer. Function literals are the closure you write; method values are the closure the compiler writes.
Escape analysis. If a closure outlives the function — you return it, you store it on a struct, you pass it to another goroutine — the captured variables cannot stay on the stack. They are allocated on the heap. A handler that closes over a 10 MiB buffer keeps that buffer until the handler is dropped.
What it costs. A closure that captures nothing is about as cheap as a function pointer. A closure that captures several variables is a small heap object plus those variables if they escape. The readability cost is hidden data flow: a function literal that writes to five outer names is harder to test than a function that takes those names as parameters. Prefer parameters when the set is small and explicit.
Code Examples
package main
import "fmt"
func counter() func() int {
n := 0
return func() int {
n++
return n
}
}
func main() {
next := counter()
fmt.Println(next(), next()) // 1 2
}func snapshot(err error) {
// Captures the variable err; sees later assignments.
defer func() { fmt.Println("final", err) }()
// Captures the value at this moment.
defer func(e error) { fmt.Println("then", e) }(err)
err = fmt.Errorf("late")
}func startAll(ids []int) {
for _, id := range ids {
id := id // explicit copy; unnecessary on Go 1.22+, still clear
go func() { fmt.Println(id) }()
}
}Common Gotchas
Closures see later assignments
`defer func() { log(err) }()` is what you want for errors; `defer log(err)` is not.
Shared capture is shared mutable state
two goroutines calling closures over the same `n` need a mutex or they race.
Returning a closure keeps captured locals alive
large captured slices are a common leak until the closure is unreachable.
A function literal with no captured names is still a function value
you can pass it, but it does not close over anything.