Skip to content
Codewilds

Lesson 13 of 38 · Functions

Go Closures, Function Values and defer

medium20 XP4 min read

In Go, functions are values, just like numbers and strings: you can store a function in a variable, pass it to another function and return it from one.

Add closures — functions that remember the variables around them — and defer, which schedules cleanup code, and you have the tools behind callbacks, middleware and resource handling in real Go programs.

Functions are values

package main

import "fmt"

func double(n int) int {
	return n * 2
}

// apply calls f with x and returns the result.
func apply(f func(int) int, x int) int {
	return f(x)
}

func main() {
	var op func(int) int = double
	square := func(n int) int { return n * n }

	fmt.Println(op(4), apply(square, 5), apply(double, 5))
}
8 25 10

func(int) int is a function type: it describes every function that takes one int and returns an int, so both double and square fit. square holds an anonymous function — a function literal without a name. A function that takes or returns other functions, like apply, is a higher-order function.

Pass the function itself, apply(double, 5), not its result, double(5). The zero value of a function type is nil, and calling a nil function panics.

Closures

A function literal can use the variables of the function around it. It captures them: they stay alive as long as the closure does, even after the outer function has returned.

// makeTotal returns a function that adds amount to a running total
// and returns the new total.
func makeTotal() func(int) int {
	total := 0
	return func(amount int) int {
		total += amount
		return total
	}
}

func main() {
	wallet := makeTotal()
	fmt.Println(wallet(10), wallet(5))

	other := makeTotal()
	fmt.Println(other(1), wallet(0))
}
10 15
1 15

Every call of makeTotal creates a new total variable, so wallet and other keep separate state. Closures can capture the outer function's parameters too — the building block for functions that create customised functions.

defer

defer schedules a function call to run when the surrounding function returns, whether it returns normally or because of a panic. Deferred calls run in last-in, first-out order. The deferred call's arguments are evaluated immediately, at the defer statement; only the call itself waits:

// trace prints "enter" now and returns a function that prints "exit".
func trace(name string) func() {
	fmt.Println("enter", name)
	return func() {
		fmt.Println("exit", name)
	}
}

func main() {
	defer trace("main")()
	defer fmt.Println("deferred first")
	defer fmt.Println("deferred second")
	fmt.Println("working...")
}
enter main
working...
deferred second
deferred first
exit main

trace("main") ran at once; the function it returned was deferred first, so it ran last. defer keeps cleanup right next to setup, where it can't be forgotten: defer file.Close() after opening a file, defer mu.Unlock() after locking a mutex, or a trace-style helper that measures how long a function runs.

Deferred closures, panic and recover

A deferred closure runs after the return values are set, so it can still read and change named results. Together with recover, that turns a crash into an error. A panic stops the normal flow of a function, but deferred calls still run — and calling recover() inside one of them stops the panic and returns the panic value:

// safeDivide divides a by b, turning a panic into an error.
func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

func main() {
	fmt.Println(safeDivide(7, 2))
	fmt.Println(safeDivide(1, 0))
}
3 <nil>
0 recovered: runtime error: integer divide by zero

a / b panicked, the deferred closure recovered and set err, and result kept its zero value. In everyday code you would simply check b == 0 and return an error: Go reports expected failures with error values. recover is for code that must survive panics it can't predict, like a web server that keeps serving other requests when one handler has a bug.

Common mistakes

  • Calling a nil function value: it panics. Make sure a function variable is set before you call it.
  • Expecting deferred arguments to see later changes: they were evaluated at the defer line. Defer a closure, defer func() { ... }(), when you need the final values.
  • Deferring inside a long loop: deferred calls run when the function returns, not at the end of each iteration.
  • Calling recover outside a deferred function: it returns nil and stops nothing.

Assignment

Write four functions:

  1. MakeCounter() func() int returns a counter: a function that returns 1 on its first call, 2 on the second, and so on. Every counter counts on its own.
  2. MakeMultiplier(factor int) func(int) int returns a function that multiplies its argument by factor.
  3. ApplyN(f func(int) int, n, x int) int applies f to x n times in a row and returns the result. If n is 0 or negative, it returns x unchanged.
  4. Safely(f func() int) (result int, err error) calls f and returns its result with a nil error. If f panics, Safely must not crash: it recovers and returns 0 and an error whose message contains the panic value (use fmt.Errorf with %v).
next := MakeCounter()
next(), next(), next()               // 1, 2, 3
MakeMultiplier(3)(7)                 // 21
ApplyN(MakeMultiplier(2), 3, 1)      // 8: 1 → 2 → 4 → 8
Safely(func() int { return 6 * 7 })  // 42, nil
Safely(func() int { panic("boom") }) // 0, an error containing "boom"

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Scope and closures in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 13 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.