Skip to content

Clean Up with defer

The Course
•
24 min study

Some work has to happen however a function ends: a buffer must be flushed, a lock released, a temporary change undone. Writing that cleanup before every return is repetitive, and the next person to add an early return will forget it. A defer statement schedules a function call to run when the surrounding function returns, on every path, including a panic. You write the cleanup once, next to the code that made it necessary.

Deferred calls run in last-in, first-out order: the most recently deferred runs first. The arguments of a deferred call are evaluated when the defer statement runs, not when the call finally happens.

Predict and run

Follow step as the function runs. In what order are the lines printed, and which numbers do they show?

Predict, then run Go
package main

import (
	"fmt"
)

func main() {
	step := 1
	defer fmt.Println("deferred first, saw step", step)
	step = 2
	defer fmt.Println("deferred second, saw step", step)
	step = 3
	fmt.Println("returning at step", step)
}
Check your prediction
Text
returning at step 3
deferred second, saw step 2
deferred first, saw step 1

Each deferred call kept the value step had when its defer ran. To see the final value instead, defer a closure: defer func() { fmt.Println(step) }(). The closure reads step when it runs, as on Day 1. Try it, and predict the output first.

Keep the cleanup's error

bufio.Writer collects output in memory and writes it in larger pieces. Until Flush is called, nothing may have reached the destination, and Flush is where a failed write finally shows up. Deferring out.Flush() and ignoring its result would silently lose that failure. The fix is a named result. A deferred closure can read and change a named result after the return statement has set it, so it can report the flush failure when nothing else went wrong.

Report a failed flush through a named result Go
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"strings"
)

var errClosed = errors.New("destination closed")

type brokenWriter struct{}

func (brokenWriter) Write([]byte) (int, error) {
	return 0, errClosed
}

func writeReport(w io.Writer, lines []string) (err error) {
	out := bufio.NewWriter(w)
	defer func() {
		if flushErr := out.Flush(); flushErr != nil && err == nil {
			err = fmt.Errorf("write report: %w", flushErr)
		}
	}()
	for _, line := range lines {
		if _, err := fmt.Fprintln(out, line); err != nil {
			return fmt.Errorf("write report: %w", err)
		}
	}
	return nil
}

func main() {
	var page strings.Builder
	fmt.Println(writeReport(&page, []string{"tent: 3", "drill: 1"}), page.Len())
	fmt.Println(writeReport(brokenWriter{}, []string{"tent: 3"}))
}
Text
<nil> 17
write report: destination closed

The loop's writes succeeded, because they only went into the buffer. The failure appeared at Flush, after return nil, and the deferred closure turned the result into an error. The err == nil test keeps an earlier, more specific error instead of replacing it. The project's run function ends with exactly this pattern.

Recover only at a boundary

A panic unwinds the stack, running deferred calls as it goes. Inside a deferred function, recover() stops the panic and returns its value. That makes it possible to turn a panic into an ordinary error at the edge of a component. Use it sparingly: a panic means a bug, and hiding bugs is worse than crashing. Recovering is reasonable where one bad item must not take down everything else, such as one request in a server.

Turn a panic into an error at the edge Go
package main

import (
	"fmt"
)

func safely(f func()) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	f()
	return nil
}

func main() {
	values := []int{1, 2}
	fmt.Println(safely(func() { fmt.Println("Value:", values[1]) }))
	fmt.Println(safely(func() { fmt.Println("Value:", values[5]) }))
}
Text
Value: 2
<nil>
recovered: runtime error: index out of range [5] with length 2
Defer right after acquiring

Put the defer immediately after the line that creates the thing to clean up, such as out := bufio.NewWriter(w) or mu.Lock(). Then a reader sees the pair together, and no later return can slip between them.

Practice

Exercise

Your turn

Write withRollback(stock map[string]int, change func(map[string]int) error) (err error). It records a copy of stock first, then calls change. If change returns an error, a deferred function restores every key from the copy and deletes keys that were added. Show a change that succeeds and one that edits two items, then fails.

The output should be:

Text
<nil> map[drill:1 tent:2]
lamp is not sold here map[drill:1 tent:2]
Your working space Go
package main

func main() {
	stock := map[string]int{"tent": 3, "drill": 1}
	_ = stock
	// Write withRollback, then call it twice.
}
Hint 1: the idea

The deferred function can see the named result err. It only needs to restore when err is not nil.

Hint 2: a first step

Copy with maps.Clone(stock). To restore, delete every key in stock, then copy every key back from the saved map.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"maps"
)

func withRollback(stock map[string]int, change func(map[string]int) error) (err error) {
	saved := maps.Clone(stock)
	defer func() {
		if err != nil {
			for item := range stock {
				delete(stock, item)
			}
			maps.Copy(stock, saved)
		}
	}()
	return change(stock)
}

func main() {
	stock := map[string]int{"tent": 3, "drill": 1}
	err := withRollback(stock, func(s map[string]int) error {
		s["tent"]--
		return nil
	})
	fmt.Println(err, stock)
	err = withRollback(stock, func(s map[string]int) error {
		s["drill"]--
		s["lamp"] = 4
		return errors.New("lamp is not sold here")
	})
	fmt.Println(err, stock)
}
Text
<nil> map[drill:1 tent:2]
lamp is not sold here map[drill:1 tent:2]

The failed change had already lowered drill and added lamp; the deferred function undid both. fmt.Println prints maps with sorted keys, so the output is deterministic. On Day 4 you will meet the opposite design, which never touches the real map until everything has succeeded.

Was this article helpful?

Your response is saved on this device.