Rez Moss

Rez Moss

Digital Reflections: Exploring Tech, Innovation & Ideas

Go defer: How It Works, LIFO Order and Common Pitfalls

May 2021

defer schedules a function call to run when the surrounding function returns, whether it returns normally, returns early with an error, or panics. If you defer several calls, they run in reverse order, last in first out. The arguments are evaluated right away, at the defer line, even though the call itself waits.

Those three rules explain most defer bugs. Below, each one gets a real program and its output from Go 1.26.

Cleanup next to the thing you opened

The classic use is closing a resource right after you get it, so the cleanup can’t be forgotten on some early return:

func readFile(name string) (string, error) {
	f, err := os.Open(name)
	if err != nil {
		return "", err
	}
	defer f.Close()

	data, err := io.ReadAll(f)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

Both return paths close the file. The same pattern covers mu.Lock() followed by defer mu.Unlock(), rows.Close() after a database query, and resp.Body.Close() after an HTTP call. Always check the error first and defer after it. If os.Open failed, f is nil and there’s nothing to close.

(For reading a whole file, os.ReadFile does all of this in one call. The longer version is here to show defer.)

Last in, first out

Deferred calls go on a stack. This loop defers three prints:

func order() {
	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred", i)
	}
	fmt.Println("function body done")
}
function body done
deferred 3
deferred 2
deferred 1

That order is what you want for cleanup: if you open a database, then begin a transaction, the transaction gets closed before the database.

Arguments are evaluated at the defer line

This is the one that surprises people. The deferred call keeps the argument values from the moment you wrote defer. A closure, on the other hand, reads the variable when it finally runs:

func argsEvaluatedEarly() {
	x := 1
	defer fmt.Println("defer saw x =", x)
	defer func() { fmt.Println("closure saw x =", x) }()
	x = 2
}
closure saw x = 2
defer saw x = 1

So if you want the final value, wrap the call in a func() { ... }(). If you want a snapshot, pass it as an argument.

Changing the return value and recovering from panics

A deferred closure can read and change named return values, because it runs after the return statement sets them but before the caller gets them. That’s handy for adding context to every error a function returns:

func wrapErr() (err error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("wrapErr: %w", err)
		}
	}()
	return errors.New("disk full")
}

This prints wrapErr: disk full. The %w verb keeps the original error inside, so errors.Is still works on it. There’s more on that in Go error handling best practices.

recover() only works inside a deferred function, and it’s the only way to stop a panic from crashing the goroutine:

func divide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

divide(10, 2) returns 5 <nil>, and divide(1, 0) returns 0 recovered: runtime error: integer divide by zero instead of crashing. Use this at boundaries, like an HTTP handler or a worker loop, and not as a replacement for returning errors.

The loop trap

Deferred calls run when the function returns, not when the loop iteration ends. This keeps every file open until the whole function is done:

for _, name := range names {
	f, err := os.Open(name)
	if err != nil {
		return err
	}
	defer f.Close() // runs only after the loop and the function finish
	// ...
}

With a few files that’s harmless. With ten thousand you hit the open-file limit. Move the body into its own function so each defer runs at the end of each call:

for _, name := range names {
	if err := processFile(name); err != nil {
		return err
	}
}

func processFile(name string) error {
	f, err := os.Open(name)
	if err != nil {
		return err
	}
	defer f.Close()
	// ...
	return nil
}

The other cost people worry about is speed. Since Go 1.14, most defers are open-coded by the compiler and cost close to a normal function call, so performance is not a reason to avoid defer in normal code.

Defer pairs well with goroutines too: defer wg.Done() at the top of a worker makes sure a sync.WaitGroup never hangs, even if the worker returns early. The worker pools in the Go channels examples use a WaitGroup the same way, and if you’re wondering where else Go runs code for you automatically, Go’s init() function is the other half of that story.

comments powered by Disqus