The cleanup problem
Functions that acquire resources (open files, lock mutexes, establish database connections) must release them when done. The release call should always happen, regardless of how the function exits: normal return, early return due to an error, or an unexpected failure.
Without a dedicated mechanism, ensuring cleanup is manual and error-prone. Every early return needs its own matching cleanup call, and adding a new exit path means auditing every existing one. Go's defer statement takes care of this.
What defer does
A defer statement schedules a function call to be executed just before the surrounding function returns. The call is registered immediately when the defer line is reached, but the actual execution is postponed:
func main() { fmt.Println("start") defer fmt.Println("deferred") fmt.Println("end")}Output:
start
end
deferred
The deferred call runs last, after the rest of main has finished.
When a deferred function executes
A deferred function is guaranteed to run under three conditions:
- The surrounding function returns: a
returnstatement anywhere in the function triggers deferred calls before control goes back to the caller. - Execution reaches the end of the function body: an implicit return at the closing brace.
- The function panics: even an unrecovered panic will drain the deferred call stack before unwinding.
In all three cases, the deferred function runs before the surrounding function hands control back.
Arguments are evaluated immediately
When defer registers a call, it evaluates the function's arguments right then, not when the deferred call eventually runs:
func main() { x := 10 defer fmt.Println(x) // captures 10 now x = 20 fmt.Println(x)}Output:
20
10
fmt.Println(x) is registered with x = 10. Even though x is later changed to 20, the deferred call still prints 10. The argument was frozen at the moment the defer statement was evaluated.
Multiple defers run in LIFO order
When a function registers more than one deferred call, they run in last-in, first-out order, like a stack. The last defer registered runs first:
func main() { defer fmt.Println("first") defer fmt.Println("second") defer fmt.Println("third")}Output:
third
second
first
The LIFO order is intentional and matches how resources nest: if you open A and then B, the correct cleanup order is to close B first and A last, which is the order the deferred calls run in.
Defer and return values
A deferred call runs after the return statement sets the result parameters, but before the function returns to its caller. For functions with named return values, this means a deferred function can read and modify the value that will actually be returned:
func double() (n int) { defer func() { n *= 2 }() n = 5 return}fmt.Println(double()) // 10The return statement sets n to 5. The deferred function then runs, multiplies n by 2, leaving it at 10. The caller receives 10, not 5.
This interaction only applies to named return values. With unnamed return values, the deferred function cannot reach the return value at all:
func double() int { n := 5 defer func() { n *= 2 // too late: the return value was already copied }() return n // copies n now; the deferred change won't reach it}fmt.Println(double()) // 5So when a deferred function needs to adjust what gets returned, use named return values.
Cleaning up resources
The most common use of defer is ensuring a resource is released when the function that opened it exits. The canonical example is a file:
func processFile(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() // read from f... return nil}f.Close() is registered immediately after the file is opened successfully. No matter how many return statements follow (one for each possible error, plus the final success return), f.Close() runs exactly once, just before processFile hands control back.
The same pattern applies to any resource with a paired acquire/release:
mu.Lock()defer mu.Unlock()rows, err := db.Query(query)if err != nil { return err}defer rows.Close()Each defer is placed right next to the acquisition it protects. The code reads in the order things happen, and cleanup runs without repeated release calls scattered through the function.
Defer and panics
A panic in Go unwinds the call stack, running deferred functions along the way. This means defer is also how you recover from a panic: a deferred function can call recover() to intercept the panic and prevent the program from crashing.
Panic and recovery have their own article. The part that matters here is that cleanup registered with defer still runs when a function panics, so one defer handles both normal exits and unexpected failures.