The Analogy: The Shared Notebook
Two clerks are told to keep track of the day's takings. If you photocopy the ledger page and give each of them a copy, they will disagree by lunchtime. If instead you tell them both "page 14 of the notebook on the shelf", they will always agree, because there is one page and they are both writing on it. Nothing about the arrangement copies anything: they were each handed a reference to where the number lives.
A Go closure is a function that was handed one of those references. When a function literal mentions a variable from the function around it, it does not receive that variable's current value — it receives the variable itself. The literal and its enclosing function share the storage, so a write through either is visible through the other, forever, including long after the enclosing function has returned. This is the single fact that explains every closure behaviour, helpful and surprising alike.
That the page outlives the clerk is the second consequence. A local variable normally dies with its function call, but if a closure captured it, the compiler notices and puts the variable somewhere that survives — the heap — and the garbage collector keeps it alive as long as any closure still refers to it. Returning a function that holds a local variable is correct Go, not a dangling reference. The flip side is retention: a closure that captured a ten-megabyte buffer keeps ten megabytes alive for as long as anything holds the closure.
The third consequence is why closures and goroutines need care. Two closures capturing the same variable are two writers on one page, and that is precisely what you want for a counter and precisely what corrupts data when the two clerks work simultaneously. Go 1.22 removed the most common version of this bug by giving each loop iteration its own variable, but it did not change the capture rule — it changed how many variables there are to capture. Module 6 covers what to do when the writers run concurrently.
Syntax or Core Structure
An immediately-invoked literal, a pair of closures sharing one variable, capture-by-reference, and per-iteration loop variables.
package main
import "fmt"
// Both returned functions capture the same n.
func counter() (next func() int, reset func()) {
n := 0
next = func() int { n++; return n }
reset = func() { n = 0 }
return next, reset
}
func main() {
// An anonymous function, declared and called on the spot.
func(msg string) { fmt.Println("iife:", msg) }("hello")
next, reset := counter()
// Calls in one expression are evaluated left to right, by spec.
fmt.Println(next(), next(), next())
reset()
fmt.Println("after reset:", next())
// A second call to counter() creates a second, independent n.
other, _ := counter()
fmt.Println("other:", other(), "first:", next())
// Capture is by reference: the closure sees writes made later.
msg := "before"
show := func() { fmt.Println("show:", msg) }
msg = "after"
show()
// Go 1.22 and later: each iteration declares its own i.
var fns []func() int
for i := 0; i < 3; i++ {
fns = append(fns, func() int { return i })
}
fmt.Println(fns[0](), fns[1](), fns[2]())
}
Output (with a go.mod declaring go 1.22 or later):
iife: hello
1 2 3
after reset: 1
other: 1 first: 2
show: after
0 1 2
The last line is the version-sensitive one: on Go 1.21, or in a module whose go directive is below 1.22, all three closures capture one shared i and the line prints 3 3 3. Everything else here behaves identically on every version of Go, including show: after — the closure was created while msg said "before" and still printed the later value, because it captured the variable rather than reading it.
Technical Depth: Capture, Lifetime, Loops and Cost
What gets captured
| The literal mentions | It captures | Effect |
|---|---|---|
| A variable of the enclosing function | The variable | Reads see the latest value; writes are visible outside. |
| Its own parameter | Nothing — parameters are its own locals | Each call gets fresh storage. This is the standard way to snapshot a value. |
| A package-level variable | Nothing — globals are already shared | No environment entry is created. |
| A constant or a type | Nothing | Resolved at compile time. |
| The receiver, inside a method | The receiver variable | A value receiver is already a copy; a pointer receiver shares the object. |
The practical rule: to snapshot, pass it in. func(v int) func() { return func() int { return v } }(x) freezes x at the moment of the call, because v is a parameter and therefore a new variable each time.
Lifetime and escape
A captured variable is moved to the heap if the closure outlives the enclosing call — returned, stored in a slice, sent to a goroutine, or deferred past the return. go build -gcflags=-m reports this as "moved to heap". Two consequences follow. Creating a closure that captures anything is usually one allocation, which matters in a hot loop and nowhere else. And the closure is a garbage-collection root for everything it captured, so a long-lived callback holding a request's parsed body keeps that body alive for the callback's lifetime, not the request's.
The loop variable, before and after Go 1.22
| Loop | Go 1.21 and earlier | Go 1.22 and later |
|---|---|---|
for i := 0; i < n; i++ | One i for the whole loop | A new i per iteration |
for i, v := range xs | One i and one v | New i and v per iteration |
for i = 0; ... (assignment, not :=) | One i | Still one i — the variable is not declared by the loop |
The change is gated by the go directive in go.mod, not by the toolchain version, so a module that still says go 1.21 compiles with the old semantics even on the newest compiler. Two habits keep code correct on both: pass the value in as an argument (go func(v int) { ... }(v)), or index the container directly (&items[i]). Both read as deliberate, which is a virtue in code someone else will have to date-check.
Closures versus a struct with methods
They are the same tool. A closure is an object with one method and hidden fields; a struct with methods is a closure with named fields and several entry points. Choose by counting: one operation over one or two captured values reads better as a closure, and anything with three pieces of state, several operations, or a need to be inspected in a debugger reads better as a struct. The counter above is right at the boundary, which is why it returns two functions rather than four.
Where anonymous functions earn their place
// Scope a defer to a loop iteration without extracting a function.
for _, name := range files {
func() {
f, err := os.Open(name)
if err != nil {
return
}
defer f.Close() // runs at the end of THIS iteration
process(f)
}()
}
// Initialise a package-level variable that needs statements.
var pattern = func() *regexp.Regexp {
return regexp.MustCompile(`^[a-z]+$`)
}()
They also show up in stack traces as main.main.func1, which is worth knowing when a panic points at a literal rather than a name.
Real World Example: An Undo Stack Made of Closures
Every edit returns a function that reverses it. The operations share one document; each undo function carries its own coordinates.
package main
import (
"fmt"
"slices"
"strings"
)
// Returns three closures over one shared lines variable.
func newEditor(initial []string) (
insert func(int, string) func(),
remove func(int) func(),
dump func() string,
) {
lines := slices.Clone(initial)
insert = func(i int, s string) func() {
lines = slices.Insert(lines, i, s)
// i is this call's own parameter; lines is shared.
return func() { lines = slices.Delete(lines, i, i+1) }
}
remove = func(i int) func() {
old := lines[i]
lines = slices.Delete(lines, i, i+1)
return func() { lines = slices.Insert(lines, i, old) }
}
dump = func() string { return strings.Join(lines, "|") }
return insert, remove, dump
}
func main() {
insert, remove, dump := newEditor([]string{"alpha", "beta"})
var undo []func()
push := func(f func()) { undo = append(undo, f) }
push(insert(2, "gamma"))
fmt.Println("1:", dump())
push(insert(0, "intro"))
fmt.Println("2:", dump())
push(remove(2))
fmt.Println("3:", dump())
for len(undo) > 0 {
last := undo[len(undo)-1]
undo = undo[:len(undo)-1]
last()
fmt.Println("undo:", dump())
}
}
Output:
1: alpha|beta|gamma
2: intro|alpha|beta|gamma
3: intro|alpha|gamma
undo: intro|alpha|beta|gamma
undo: alpha|beta|gamma
undo: alpha|beta
The document works because lines is captured, not copied. Five different function values touch it — insert, remove, dump, and every undo function either of the first two produced — and they all name the same variable, so an undo written before the next two edits still edits the current document. Note that lines = slices.Insert(...) reassigns the variable, which only works because the closures share the variable itself; had they each captured a copy of the slice header, the reassignment would have been invisible to everybody else.
The undo functions demonstrate the other half of the capture rule. Each one refers to i, and i is a parameter of that particular insert or remove call, so each undo function has its own private copy frozen at the moment it was created — exactly the snapshot behaviour you get by passing a value in. remove extends the idea with old, a local variable read before the deletion and kept alive by the returned function long after remove has returned. One program, both behaviours: shared state where sharing is the point, private state where it is not.
The design has a real limitation worth naming. The indices are only valid against the document as it stood when the operation ran, so the stack must be unwound strictly last-in-first-out. Undo the second edit before the third and slices.Delete(lines, 0, 1) removes whatever now happens to be first. That is not a closure problem — it is why collaborative editors record operations that can be rebased against each other rather than raw indices — but a closure makes the fragile version so easy to write that the constraint deserves a comment in real code.
Two practical notes. lines is heap-allocated and stays alive as long as any of these functions is reachable, so dropping the closures is what releases the document; an undo stack that is never trimmed retains every removed string indefinitely. And slices.Clone, slices.Insert and slices.Delete all arrived in Go 1.21, with slices.Delete gaining tail-zeroing in 1.22 — irrelevant here, since the result is assigned straight back, but relevant the moment you keep a second reference to the old slice.
Common Mistakes
- Capturing the loop variable on Go 1.21 or in a pre-1.22 module. Every closure sees the final value. The symptom is a slice of functions that all return the same thing, or goroutines that all process the last item. Pass the value as an argument.
- Launching a goroutine that captures a variable the loop then rewrites. Even on Go 1.22 this bites when the variable is declared outside the loop, and it is a data race, not just a wrong value.
go run -racefinds it.
deferinside a loop, expecting it to run per iteration. Deferred calls run when the function returns, so a thousand-iteration loop holds a thousand files open. Wrap the body in an immediately-invoked function literal, or extract a real one.
- Assuming the closure snapshots values.
show := func() { fmt.Println(msg) }prints whatevermsgholds whenshowruns, not when it was written.
- Retaining more than you meant to. A callback registered for the lifetime of a server, capturing a request-scoped buffer, keeps that buffer out of the garbage collector's hands for the lifetime of the server.
- Creating a closure inside a hot loop. Each one that captures a variable is an allocation. Hoist it above the loop when it does not depend on the iteration, and benchmark before assuming it matters.
- Writing a recursive function literal without declaring the variable first.
f := func() { f() }does not compile becausefis not in scope inside its own initialiser. Declarevar f func()and then assign.
- Sharing one captured counter between goroutines without a mutex. Two closures incrementing the same
nconcurrently is the textbook data race; the increment is not atomic. Module 6 has the fixes.
- Using a closure where a struct belongs. Five captured variables and three returned functions is an object with the field names hidden from the debugger and from the next reader.
- Forgetting that a closure over a named result interacts with
defer. A deferred literal can read and rewrite the named results afterreturnhas chosen them, which is powerful and easy to do by accident. That is the next lesson.
- Comparing closures. Function values only compare against
nil. Two literals with identical bodies are not equal, and asking is a compile error.
Best Practices
- Pass what you want frozen as a parameter. It is one extra argument, it works on every Go version, and it states the intent.
- Keep captured state small and obvious. If a reader has to scroll up to learn what a closure touches, extract a struct.
- Wrap a loop body in a literal when you need a per-iteration
defer, and add a comment saying that is why the literal exists.
- Prefer indexing to capturing when you need a pointer to an element.
&items[i]never depended on the loop-variable rules in the first place.
- Set the
godirective ingo.modto 1.22 or later if you can. It removes an entire bug class from every loop in the module.
- Run
go vetand the race detector in CI.vetcatches the classic loop-capture pattern on old modules;-racecatches the concurrent version that no static check can see.
- Return a single closure, not a bag of them, when a caller only needs one operation. Multiple returned functions sharing state is a signal to switch to a type.
- Document what a returned function keeps alive if it captures anything expensive. The caller cannot see it from the signature.
Practice Exercises
- Write
func accumulator() func(int) intthat returns a function adding its argument to a running total and returning the new total. Call it twice to get two independent accumulators and interleave calls to prove they do not share state.
- Build a slice of five
func() intvalues inside afor i := 0; i < 5; i++loop, print their results, then change the loop to declareioutside it and print again. Explain both outputs and state which Go version your module targets.
- Write a
memofunction that wraps afunc(int) intin a cache:func memo(f func(int) int) func(int) int. Use it on a deliberately slow squaring function, call it with repeated arguments, and print a count of how many times the underlying function actually ran.
- Take the undo-stack example and add a
replace(i int, s string) func()operation. Then deliberately call the second undo function before the third and describe exactly what the document ends up containing and why.