The Analogy: The Spike on the Counter
Old shops kept a metal spike on the counter. Every bill that arrived during the day was impaled on it as it came in, and at closing time the shopkeeper worked down the spike settling them — the last one impaled sitting on top, and therefore paid first. Two details make the spike a good machine rather than just a pile of paper. The amount was written on each bill at the moment it was impaled, so nothing changed while it waited. And closing time meant closing time: the bills were settled whether the day ended calmly or with the fire alarm going off.
defer is that spike. defer f.Close() does not close anything; it impales an invoice that says "call Close on this file" and carries on. When the surrounding function returns, Go works down the spike in last-in-first-out order and makes the calls. Because you register the cleanup on the line after you acquire the thing, the two always sit next to each other in the source, and the reverse ordering falls out for free: resources are released in the opposite order to their acquisition, which is almost always what correctness requires.
The amount written on the invoice is the crucial detail, and it is where the previous lesson pays off. defer fmt.Println(i) evaluates i now and stores the value; the call happens later. defer func() { fmt.Println(i) }() stores a closure, and closures capture the variable, so it reads i at closing time. Same keyword, opposite behaviour, and the difference is entirely whether the thing you deferred takes i as an argument or captures it.
Closing time means every exit. A deferred call runs on a normal return, on an early return from the middle of a nest of ifs, and while a panic is unwinding the stack — which is why defer is Go's answer to finally and why recover only works from inside a deferred function. It does not run if the process leaves without unwinding: os.Exit, log.Fatal, an unrecoverable runtime fatality like a concurrent map write, or a goroutine that blocks forever. And there is one more capability the spike metaphor does not cover: a deferred closure can see and rewrite the function's named results after return has already chosen them, which is how Go wraps errors and turns panics back into ordinary failures.
Syntax or Core Structure
LIFO ordering, arguments evaluated at registration, closures evaluated at return, and a named result rewritten on the way out.
package main
import "fmt"
func order() {
fmt.Println("body start")
for i := 1; i <= 3; i++ {
defer fmt.Println("deferred", i) // i is evaluated here, now
}
fmt.Println("body end")
}
func snapshotVsClosure() {
x := "first"
defer fmt.Println("argument:", x) // "first" is stored now
defer func() { fmt.Println("closure:", x) }() // x is read at return
x = "second"
}
func wrap() (result string) {
defer func() { result = "[" + result + "]" }()
return "inner" // sets result, then the defer edits it
}
func main() {
order()
fmt.Println("--")
snapshotVsClosure()
fmt.Println("--")
fmt.Println(wrap())
}
Output:
body start
body end
deferred 3
deferred 2
deferred 1
--
closure: second
argument: first
--
[inner]
Three separate lessons in eleven lines of output. The order function proves the stack: three registrations, three calls in reverse, all after the body finished. snapshotVsClosure proves the timing split — the closure was registered second so it runs first, and it prints second because it captured the variable, while the plain argument still says first because the value was copied at registration. And wrap shows that return "inner" is really two steps: assign the named result, then run the spike, which is what gives the deferred closure something to edit.
Technical Depth: Timing, Ordering, Results and Cost
What is evaluated when
For defer x.M(a, b), three things are evaluated at the moment the defer statement executes, and only the call itself waits:
| Part | Evaluated at |
|---|---|
The function or method value (x.M) | Registration |
The receiver (x) | Registration |
Every argument (a, b) | Registration |
| The call | Function return |
So defer f.Close() on a variable f that is reassigned later still closes the original file. And defer conn.Close() where conn is nil at registration does not panic then — it panics when the spike is worked, unless Close tolerates a nil receiver.
Ordering, and what does not run
Deferred calls run in reverse registration order, on the same goroutine, after the results are set and before the caller resumes.
| Exit route | Defers run |
|---|---|
return, including an early one | Yes |
| Falling off the end of the function | Yes |
| A panic unwinding through the function | Yes — this is how recover gets its chance |
os.Exit, log.Fatal, log.Fatalf | No. The process leaves without unwinding. (log.Panic does unwind, because it panics.) |
| An unrecoverable runtime fatality (concurrent map write, stack exhaustion, deadlock detection) | No. |
| A goroutine that blocks forever, or the process being killed | No. |
That table is the reason log.Fatal is a poor fit anywhere except main: it silently discards every cleanup on the stack.
Named results are the hook
return v in a function with named results means "assign v to the result variable, then run the defers, then leave". A deferred closure that mentions the result variable therefore sees the chosen value and can replace it. The three standard uses:
// 1. Wrap every error path with one line of context.
func load(id string) (cfg Config, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("load %s: %w", id, err)
}
}()
// ... several return paths, none of which mention id ...
}
// 2. Turn a panic into an error (module 7 covers recover properly).
func safe() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return risky()
}
// 3. Promote a Close error without losing a real one.
func write(name string) (err error) {
f, err := os.Create(name)
if err != nil {
return err
}
defer func() {
if cerr := f.Close(); cerr != nil && err == nil {
err = cerr
}
}()
// ...
}
The third pattern matters more than it looks. Close on a file you only read can be ignored, but Close on a file you wrote is where buffered data is flushed and where a full disk finally reports itself. A bare defer f.Close() throws that error away, and the program cheerfully reports success on a truncated file.
The loop problem
Defers are tied to the function, not the block. A loop that defers accumulates registrations until the function ends:
// Wrong: every handle stays open until the whole function returns.
for _, name := range names {
f, err := os.Open(name)
if err != nil {
continue
}
defer f.Close()
process(f)
}
// Right: a literal gives the defer a scope of one iteration.
for _, name := range names {
func() {
f, err := os.Open(name)
if err != nil {
return
}
defer f.Close()
process(f)
}()
}
With a thousand names the first version holds a thousand descriptors and will hit the process limit. Extracting a named function is usually tidier than the literal; use whichever makes the intent visible.
Cost
Since Go 1.14 most defers are open-coded: the compiler inlines the call at each return path, and the overhead is a couple of nanoseconds — no reason to avoid defer on a mutex or a file. The exception is a defer whose registration count is not known at compile time, such as one inside a loop, which falls back to the heap-allocated list and costs meaningfully more. The old advice to hand-unlock mutexes for speed predates this and should be ignored unless a benchmark says otherwise.
The mutex idiom
mu.Lock()
defer mu.Unlock()
Two adjacent lines, and the unlock now happens on every return path including a panic, which is what stops a panicking request handler from wedging the whole server on a permanently held lock. When a function needs the lock for only part of its body, do not stretch the defer to cover the rest — extract the locked section into its own function and defer there.
Real World Example: Four Defer Patterns in One Function
Reverse-order release, error wrapping through a named result, and a Close error promoted only when nothing worse happened. The resources are in-memory so the transcript is reproducible.
package main
import (
"errors"
"fmt"
"strings"
)
type journal struct{ steps []string }
func (j *journal) add(format string, args ...any) {
j.steps = append(j.steps, fmt.Sprintf(format, args...))
}
type resource struct {
name string
j *journal
closeErr error
}
func open(j *journal, name string, closeErr error) (*resource, error) {
if name == "" {
return nil, errors.New("empty name")
}
j.add("open %s", name)
return &resource{name: name, j: j, closeErr: closeErr}, nil
}
func (r *resource) Close() error {
r.j.add("close %s", r.name)
return r.closeErr
}
func process(j *journal, input string, flushErr error) (n int, err error) {
// Registered first, so it runs last: it sees the final error.
defer func() {
if err != nil {
err = fmt.Errorf("process %q: %w", input, err)
}
}()
// Plain := here, not inside an if, so err IS the named result.
src, err := open(j, "source", nil)
if err != nil {
return 0, err
}
defer src.Close() // read-only: its error genuinely does not matter
dst, err := open(j, "sink", flushErr)
if err != nil {
return 0, err
}
// A write target: promote the close error, but never mask a real one.
defer func() {
if cerr := dst.Close(); cerr != nil && err == nil {
err = cerr
}
}()
if strings.TrimSpace(input) == "" {
return 0, errors.New("nothing to copy")
}
j.add("copy %d bytes", len(input))
return len(input), nil
}
func main() {
cases := []struct {
input string
flushErr error
}{
{"hello", nil},
{" ", nil},
{"world", errors.New("disk full")},
}
for _, c := range cases {
var j journal
n, err := process(&j, c.input, c.flushErr)
fmt.Printf("input=%-7q n=%d err=%v\n", c.input, n, err)
fmt.Println(" steps:", strings.Join(j.steps, " -> "))
}
}
Output:
input="hello" n=5 err=<nil>
steps: open source -> open sink -> copy 5 bytes -> close sink -> close source
input=" " n=0 err=process " ": nothing to copy
steps: open source -> open sink -> close sink -> close source
input="world" n=5 err=process "world": disk full
steps: open source -> open sink -> copy 5 bytes -> close sink -> close source
Read the journal in each case and the ordering is visible: the sink is always closed before the source, because it was opened second and therefore deferred second. That is not a convention someone remembered to follow — it is the shape of the spike. Every acquisition sits one line above its release, so a reviewer checking that nothing leaks reads pairs of adjacent lines instead of tracing exit paths, and the failing case in the middle releases both resources on a path that never mentions cleanup at all.
The third case is the one to study. It returns n=5 and an error, because return len(input), nil set both named results, and only then did the deferred closure discover that Close had failed and overwrite err. The cerr != nil && err == nil guard is what keeps this honest: a flush failure is worth reporting, but never at the price of hiding the original problem that caused the function to bail out early. Callers should treat a non-nil error as making n meaningless, which is the standard Go contract and worth restating in the doc comment when a function can return both.
Registration order determines who sees what. The wrapper is deferred on the very first line, so it runs last and observes err after the Close promotion has already happened — which is why process "world": disk full comes out wrapped rather than bare. Reverse those two registrations and the wrapper would run before the close, the disk error would arrive unwrapped, and the bug would only show up in a log line nobody reads. When several defers touch the same named result, the outermost concern is registered first.
One trap is invisible in working code. Both open calls use := at the top level of the function body, so err resolves to the named result. Written as if src, err := open(...); err != nil, the := would declare a new err scoped to the if, the named result would stay nil, and the wrapper would silently do nothing on that path. go vet's shadow analysis is not enabled by default, so this is one to catch by eye: inside a function that wraps its named error, never re-declare err in an inner scope.
Common Mistakes
deferinside a loop. The calls pile up until the function returns, holding every file, connection or lock open. Wrap the body in a function literal, or extract a helper.
- Expecting arguments to be evaluated late.
defer fmt.Println(count)prints the count as it was when thedeferran. If you want the final value, defer a closure instead.
- Shadowing the named result with
:=in an inner scope. The deferred wrapper then inspects a variable nothing ever assigned, and every error escapes unwrapped.
- Ignoring the error from
Closeon something you wrote to. The flush happens inClose, so a baredefer f.Close()can report success on a file that never made it to disk.
- Deferring before checking the error that produced the resource.
f, err := os.Open(name); defer f.Close()before testingerrdefers a call on a nil*os.File. Check first, defer second.
- Using
log.Fatalin library code. It skips every defer on the stack, so nothing is flushed, unlocked or rolled back. Return an error and letmaindecide to exit.
- Registering defers in the wrong order when they interact. The last thing registered runs first. If a wrapper must observe what another defer did, register the wrapper earlier.
- Deferring a method on a variable you are about to reassign. The receiver is captured at registration, so the cleanup targets the old value.
- Assuming a defer runs on another goroutine's exit. Defers are per-function and per-goroutine; a panic in one goroutine unwinds only that goroutine before killing the process.
- Stretching one defer over a function that only needs the lock briefly. Holding a mutex for an unnecessary hundred lines is a throughput bug that looks like tidy code.
- Deferring
recover()directly.defer recover()does not stop a panic;recoveronly works when called from inside a deferred function, so it must bedefer func() { recover() }().
Best Practices
- Defer the release on the line after the acquisition succeeds. The adjacency is the whole benefit; anything further away is a leak waiting for a new early return.
- Give the function named results whenever a defer needs to touch them, and say so in a comment so nobody "tidies" the names away.
- Promote
Closeerrors on writers, ignore them on readers, and use thecerr != nil && err == nilguard so the first failure wins.
- Register the error wrapper first. It then runs last and sees everything the other defers did.
- Keep
log.Fatalandos.Exitinmain. Everywhere else, return the error so the spike gets worked.
- Use a function literal to scope a defer to a loop iteration, with a one-line comment explaining that this is why the literal exists.
- Reach for
defer mu.Unlock()by default, and extract a smaller function when the lock should not cover the whole body.
- Do not micro-optimise defers away. They are open-coded and nearly free; the only version worth measuring is one registered inside a loop.
Practice Exercises
- Write a function that defers four
fmt.Printlncalls with the values 1 to 4, then predict the output before running it. Change one of them to a closure that reads a variable you modify afterwards, and predict again.
- Write
func parse(s string) (n int, err error)that wraps every error path with the input using a single deferred closure, and returns three distinct errors from three different branches. Verify all three come out wrapped, then deliberately shadowerrin one branch and observe what changes.
- Build a fake
Closertype whoseClosereturns an error, and a function that both fails in the body and fails on close. Prove that the body's error is the one the caller sees, then swap the guard's condition and describe what is now lost.
- Write a loop over five names that defers a print for each, and then rewrite it so each print happens at the end of its own iteration. Count the deferred calls outstanding at the midpoint of each version and explain the difference in resource terms.