Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 147 ยท Functions

Anonymous Functions and Closures

Learn Go function literals and closures - capturing variables, counters and generators, the per-iteration loop variable change in Go 1.22, function types, callbacks and immediately invoked functions.

In Go, functions are values. You can store one in a variable, pass it to another function, return it from a function, and, importantly, write one without a name right where you need it. A function written like that is called an anonymous function or function literal. When such a function uses variables from the code around it, it becomes a closure: it carries those variables with it, even after the surrounding function has returned.

Closures are everywhere in real Go: sort.Slice takes one, http.HandleFunc takes one, defer usually runs one, and goroutines start with one. This lesson explains how they work, builds counters and generators, covers the loop-variable change that arrived in Go 1.22, and shows function types and callbacks. If you haven't yet, read Functions first.

Function literals

A function literal looks like a normal function declaration without the name. You can assign it to a variable and call it:

Go Assigning a function literal to a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The variable square has the function type func(int) int, printed by %T. A function type is defined by its parameter and result types; parameter names don't matter. Because functions are values, square can be passed around like any other variable.

Calling a literal immediately

Add () after the closing brace and the literal runs on the spot. This is useful to compute a value that needs several statements, or to create a small scope:

Go An immediately invoked function literal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You'll see this form most often with go func() { ... }() and defer func() { ... }(), where the call is required: Goroutines and defer rely on it.

Closures capture variables

A function literal can read and write variables from the function around it. It captures the variables themselves, not copies of their values at that moment:

Go A closure sees later changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both closures share the one message variable. Changes made inside are visible outside and the other way round. This is different from passing an argument, which always copies.

Counters and generators

A closure can keep private state that outlives the function that created it. The classic example returns a function that increments a hidden counter:

Go Each counter has its own hidden state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

count would normally disappear when newCounter returns, but the returned function still refers to it, so Go keeps it alive. Each call to newCounter creates a new count, which is why a and b count independently. Go's escape analysis moves such a variable to the heap automatically (Stack, Heap and Escape Analysis explains how).

The same idea builds generators, functions that produce a sequence one value at a time:

Go A Fibonacci generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

for range 10 loops ten times without a counter variable (range over an integer, Go 1.22). Today the idiomatic way to produce sequences is often an iterator, but closures are the mechanism underneath them.

Closures in loops: the Go 1.22 change

Before Go 1.22 a for loop had one variable shared by all iterations. Closures created in the loop all captured that single variable, so after the loop they all saw its final value. It was one of the best-known Go gotchas.

Since Go 1.22, every iteration gets its own copy of the loop variable (for loops that declare their variable with := or range). Closures now capture what you expect:

Go Each iteration has its own variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

This prints 0, 1 and 2. On Go 1.21 and earlier it would print 3 three times. The new behavior applies to modules whose go.mod says go 1.22 or later; older modules keep the old rule so existing code doesn't change meaning. for Loops has the details.

A variable declared outside the loop is still shared, of course:

Go A shared variable is still shared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The three results are 30, 31 and 32: each closure has its own i (0, 1, 2), but they all see the one shared variable, which ended at 30.

Per-iteration variables fixed the loop variable problem, not capturing in general. If a goroutine or closure reads a variable that another part of the program changes, you still need synchronization. See Data Races and the Memory Model.

Function types and callbacks

You can give a function type a name with type. Doing so documents intent and lets you attach methods later. A callback is simply a function passed as an argument for the callee to call:

Go Named function types and callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second call passes a literal inline that captures prefix and suffix. That is the real power of closures: the callee doesn't need parameters for the caller's context, because the function already has it. Functions as Values and Higher-Order Functions builds on this.

Closures that hold resources

Closures are a neat way to make small stateful helpers, such as a function that remembers the last value it saw:

Go A closure that remembers the previous value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For anything with more than a couple of pieces of state, or state you want to inspect and test, a struct with methods is clearer than a closure.

Recursive literals

A function literal can't call itself by name because the variable isn't declared yet while the literal is being evaluated. Declare the variable first:

Go
var walk func(n int)
walk = func(n int) {
	if n == 0 {
		return
	}
	fmt.Println(n)
	walk(n - 1)
}
walk(3)

Recursion uses this pattern for local helpers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print?

    f := newCounter(); f(); f(); fmt.Println(f()), where newCounter returns a function that increments and returns a captured count starting at 0.

    The closure keeps its captured count between calls, so the third call returns 3.
  2. 2. In Go 1.22 or later, what do closures created inside for i := 0; i < 3; i++ capture?

    Go 1.22 gives each iteration its own variable, so closures that remember i see 0, 1 and 2.
  3. 3. What is the type of func(a, b int) string { return "" }?

    A function type consists of the parameter types and result types. Parameter names are not part of it.
  4. 4. Two counters a := newCounter() and b := newCounter() are created. Do they share state?

    Every call to newCounter allocates its own count variable, so a and b are independent.
  5. 5. Why is the form func() { ... }() common with defer and go?

    Both defer and go take a function call. A literal followed by () is a call, and it can capture surrounding variables.

Summary

  • A function literal is a function without a name; it is a value you can assign, pass and return, and call immediately with ().
  • A closure captures variables from its surrounding scope, not copies, so changes are visible both ways.
  • Returning a closure gives you private state that lives as long as the closure does (counters, generators, detectors).
  • Since Go 1.22 each iteration of a for loop has its own loop variable, which fixes the old closure-in-loop bug; variables declared outside the loop are still shared.
  • Function types (type Transform func(string) string) name a signature and are the basis of callbacks.
  • For a function literal to call itself, declare the variable first, then assign the literal.

Next: defer explains how to schedule cleanup work to run when a function returns.