Go Closures and Anonymous Functions Explained

Updated 4 min read
Go Closures featured image: cards for anonymous functions, state and factories

Go closures are functions that remember the variables around them, even after the outer function has finished. In this post, you will write anonymous functions and build a counter that keeps its own state. Then you will create functions that make other functions. Each idea comes with a short example.

Closures build on the basics from writing and calling functions in Go. They also appear inside goroutines all the time, which you met in goroutines in Go for beginners.

Anonymous Functions First

An anonymous function is simply a function without a name. You can store it in a variable, pass it to another function or run it right away.

greet := func(name string) string {
	return "Hello, " + name
}
fmt.Println(greet("Asha")) // Hello, Asha

func(msg string) {
	fmt.Println(msg)
}("runs right away") // runs right away

The second example ends with ("runs right away"), so Go calls it immediately. Developers often use this style with defer and go.

What Are Go Closures?

A closure is an anonymous function that uses a variable from outside its own body. The function “closes over” that variable and keeps it alive. For example, think of a backpack. Wherever the function goes, it carries its variables along.

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

next := counter()
fmt.Println(next(), next(), next()) // 1 2 3

other := counter()
fmt.Println(other()) // 1

Normally, count would vanish when counter returns. However, the inner function still uses it, so Go keeps it alive. The diagram below shows why next and other keep separate counts.

Go Closures diagram showing two counters that each remember their own count variable

Each call to counter() creates a fresh count variable, and each returned closure carries its own copy along.

Go Closures as Function Factories

func multiplier(n int) func(int) int {
	return func(x int) int { return x * n }
}

double := multiplier(2)
triple := multiplier(3)
fmt.Println(double(5), triple(5)) // 10 15

In short, multiplier is a factory. It builds new functions, and each one remembers its own n. This pattern also creates HTTP middleware and custom validators.

Closures as Callbacks

people := []string{"Ravi", "Asha", "Meera"}
sort.Slice(people, func(i, j int) bool {
	return people[i] < people[j]
})
fmt.Println(people) // [Asha Meera Ravi]

Here the closure reads people from the outer scope. So sort.Slice only needs a tiny “less than” rule from you.

Changing Outer Variables

total := 0
add := func(n int) { total += n }
add(10)
add(5)
fmt.Println(total) // 15

A closure shares the variable itself, not a copy of its value. As a result, changes inside the closure are visible outside too.

Go Closures in Loops

var funcs []func()
for i := 0; i < 3; i++ {
	funcs = append(funcs, func() { fmt.Print(i, " ") })
}
for _, f := range funcs {
	f()
}
// Go 1.22 and later: 0 1 2

Before Go 1.22, every closure in this loop shared one i, so the program printed “3 3 3”. Since Go 1.22, however, each loop iteration gets a fresh variable. Therefore, Go closures created in a loop now behave the way most people expect. Make sure your go.mod says go 1.22 or later to get this behaviour.

When to Use Go Closures

Use Go closures when a small piece of behaviour needs a little private state. For example, a rate limiter can remember when it last ran. Likewise, an ID generator can remember the last number it used. Closures also keep helper code next to the place that uses it.

However, a closure is not always the best tool. If the state grows large or needs many methods, a struct with methods is clearer. In short, choose a closure for one small job and a struct for anything bigger.

Common Mistakes with Go Closures

Problem you seeWhy it happensHow to fix it
Loop prints the last value every timeThe module uses Go 1.21 or older.Raise the go line in go.mod to 1.22 or later.
Data race warning with goroutinesMany closures change one variable together.Protect it with a mutex or use channels.
Memory stays in useA long-lived closure keeps a large variable alive.Capture only the small value you need.

The data race case is common, so revisit the Go sync package if it sounds new. Closure questions are also an interview favourite, so try my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • An anonymous function has no name and can run immediately.
  • Go closures remember the variables they use from outside.
  • Each call to a factory function creates fresh captured variables.
  • Closures share variables, so changes are visible outside.
  • Since Go 1.22, each loop iteration gets its own variable.

What’s Next?

Functions can now remember state. Next, we will see what happens when a program crashes and how defer, panic and recover handle it.

Next lesson: Go Panic and Recover with Defer Explained