Functions that remember
The previous article introduced function literals: anonymous functions assigned to variables or passed as arguments. A closure goes one step further. It is a function literal that also captures the state of the scope it was created in.
Idiomatic Go uses closures often to build functions that carry their own private memory, independent of any caller.
Anonymous functions
A named function declaration binds a name at the package level and is visible anywhere in the package. Sometimes you need a small piece of logic that is only relevant in one place and doesn't need a permanent name. An anonymous function (also called a function literal or lambda) is declared inline, without a name:
func() { fmt.Println("no name needed")}()The () at the end calls the function immediately after defining it. This is called an immediately invoked function expression, and it is useful for running setup logic in a tight scope.
More commonly, anonymous functions are assigned to a variable:
double := func(n int) int { return n * 2}fmt.Println(double(5)) // 10double holds a function value. It can be called, passed to other functions, or stored in a data structure, like any other value.
Anonymous functions are also the natural choice for callbacks: short, one-off behavior passed into a function that calls it later. The standard library uses this pattern extensively:
numbers := []int{5, 2, 8, 1, 9, 3}sort.Slice(numbers, func(i, j int) bool { return numbers[i] < numbers[j]})fmt.Println(numbers) // [1 2 3 5 8 9]sort.Slice takes the comparison logic as a function argument. The comparison is only used here, so it makes sense to write it at the call site.
What makes a closure
An anonymous function becomes a closure the moment it references a variable from the scope that surrounds it. The function doesn't receive that variable as a parameter. It closes over it, capturing a reference to the variable itself:
func counter() func() int { count := 0 return func() int { count++ return count }}counter declares a local variable count and returns an anonymous function. That returned function references count, a variable that lives in counter's scope, not its own.
increment := counter()fmt.Println(increment()) // 1fmt.Println(increment()) // 2fmt.Println(increment()) // 3Each call to increment reads and modifies count. The variable persists between calls. Even though counter has already returned and its stack frame is gone, count stays alive because the closure still references it.
That is what defines a closure: it keeps access to the variables it closed over even after the enclosing scope has finished executing.
Each closure has its own state
Calling counter a second time does not share the same count. Each call creates a fresh execution of counter, a fresh count variable, and a fresh closure that closes over that new variable:
a := counter()b := counter()fmt.Println(a()) // 1fmt.Println(a()) // 2fmt.Println(b()) // 1 — b has its own count, starting from zerofmt.Println(a()) // 3 — a continues from where it left offa and b are completely independent, each a function paired with its own private state. That is why a closure is often described as a function with associated state: the state is neither global nor passed in, and only the closure can reach it.
Closures with multiple operations
A closure can expose more than one operation over the same captured state. The simplest way is to return multiple functions from the same enclosing scope, and they all share the same variable:
func newStack() (func(int), func() int) { items := []int{} push := func(n int) { items = append(items, n) } pop := func() int { if len(items) == 0 { return -1 } top := items[len(items)-1] items = items[:len(items)-1] return top } return push, pop}Both push and pop close over the same items slice. Either operation modifies the shared state, and the other immediately sees the change:
push, pop := newStack()push(10)push(20)push(30)fmt.Println(pop()) // 30fmt.Println(pop()) // 20Grouping related operations over shared private state like this is a lightweight alternative to a struct with methods when the data does not need to be exposed or named.
Memoization
Memoization is a technique where a function caches its results so that repeated calls with the same argument skip the computation entirely. A closure fits this well: the cache lives in the closed-over scope, where callers can't see it, and persists across calls:
func memoize(fn func(int) int) func(int) int { cache := map[int]int{} return func(n int) int { if result, ok := cache[n]; ok { return result } result := fn(n) cache[n] = result return result }}memoize wraps any func(int) int and returns a new function that transparently caches results. The cache map is private, so callers cannot inspect or modify it:
slowSquare := func(n int) int { // imagine this is expensive return n * n}square := memoize(slowSquare)fmt.Println(square(4)) // computed: 16fmt.Println(square(4)) // cached: 16fmt.Println(square(7)) // computed: 49The same memoize wrapper works for any func(int) int: you write the cache logic once and pass in the function to cache. That works because functions are first-class values and closures can carry private state.
When to use closures
Closures appear naturally in a few recurring situations:
- Callbacks: passing short, context-specific behavior to a function that calls it later (
sort.Slice,http.HandleFunc, etc.) - Factories: functions that create and return configured functions (
multiplier,memoize,counter) - Encapsulated state: when you need a stateful helper but a full struct feels like overkill
Closures don't replace structs and methods. When the state is complex, needs multiple fields, or must be passed around by name, a struct is clearer. Use a closure when the state is small, like a counter or a cache, and what you are passing around is the behavior.