defer
defer schedules a function call to run when the surrounding function exits, no matter how it exits. It is Go's tool for cleanup: unlock this mutex, close this file, stop this timer.
Detailed Explanation
You open a file, read from it, and hit five different error paths. Without defer you write f.Close() before every return. Miss one and you leak a file descriptor. defer f.Close() next to the os.Open call handles all five paths at once, and it stays correct when someone adds a sixth.
The rule: the deferred call runs when the function returns. Not at the end of the block, not at the end of the loop iteration — at function exit. That is different from a C++ destructor or a Rust drop, which fire at end of scope.
Order is LIFO. Deferred calls stack up and unwind in reverse. That matches how resources nest: you acquire A, then B, so you release B, then A.
Arguments are evaluated when you write defer, not when the call runs. This is the single most surprising part. defer fmt.Println(x) captures the value of x at that moment. If you want the value at exit time, defer a closure instead: defer func() { fmt.Println(x) }(). The closure captures the variable, not the value.
Defers run during a panic too. As a panic unwinds the stack it executes every pending deferred call. That is what makes defer a cleanup primitive rather than a convenience: your mutex still unlocks when something explodes. It is also the only place recover can be called.
Where you will actually use it:
| Pattern | Why |
|---|---|
defer mu.Unlock() right after mu.Lock() | The unlock cannot be skipped by an early return |
defer f.Close() on a file you only read | Read errors already surfaced; the close error carries no new information |
defer resp.Body.Close() after an HTTP request | Not closing it leaks the connection out of the pool |
defer cancel() after context.WithTimeout | cancel releases the timer; skipping it is a documented leak |
Ignoring Close() on a writer is a bug. Writes are buffered. The failure you care about — disk full, broken pipe, quota exceeded — often surfaces only when the buffer is flushed during Close. defer f.Close() on a file you wrote to throws that error away and reports success on a truncated file. Use a named return and a deferred closure that assigns the close error.
Defer in a loop accumulates. Each defer inside a loop body adds to the function's defer list; none of them run until the function returns. Loop over ten thousand files and you hold ten thousand descriptors. Move the body into its own function (or an immediately-invoked closure) so each iteration gets a real exit point.
What it costs. Since Go 1.14 most defers are "open-coded" and inlined into the return path, costing a few nanoseconds. Defers inside a loop or a conditional fall back to a heap-allocated list and cost more. It matters only in genuinely hot loops; measure before you contort readable code.
Code Examples
package main
import "fmt"
func main() {
// Deferred calls run last-in-first-out at function exit.
defer fmt.Println("third")
defer fmt.Println("second")
fmt.Println("first")
x := 1
// The argument is evaluated right here, so this captures 1.
defer fmt.Println("x at defer time:", x)
// A closure captures the variable, so this sees the final value.
defer func() { fmt.Println("x at run time:", x) }()
x = 2
}
// Output:
// first
// x at run time: 2
// x at defer time: 1
// second
// thirdWriting a file: the Close error is the one that matters, because that is
// Writing a file: the Close error is the one that matters, because that is
// where a buffered write actually reaches the disk.
func writeReport(path string, data []byte) (err error) {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
cerr := f.Close()
// Only report the close error if nothing has already failed.
if err == nil {
err = cerr
}
}()
_, err = f.Write(data)
return err
}Wrong: every file stays open until processAll returns.
// Wrong: every file stays open until processAll returns.
func processAll(paths []string) error {
for _, p := range paths {
f, err := os.Open(p)
if err != nil {
return err
}
defer f.Close() // piles up on the function's defer list
if _, err := io.Copy(io.Discard, f); err != nil {
return err
}
}
return nil
}
// Right: give each iteration its own function, so each gets its own exit.
func processAllFixed(paths []string) error {
for _, p := range paths {
if err := processOne(p); err != nil {
return err
}
}
return nil
}
func processOne(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // runs when processOne returns, once per file
_, err = io.Copy(io.Discard, f)
return err
}Common Gotchas
Arguments are frozen at defer time
`defer log.Println(err)` records whatever `err` held on that line, which is usually `nil`. Defer a closure if you need the value as of function exit.
`defer f.Close()` on a writer hides data loss
the flush happens inside `Close`, so a full disk or a broken pipe is reported there and thrown away. Capture it through a named return.
Defer in a loop does not release per iteration
the calls queue until the whole function returns, so long loops hold every handle at once. Extract the body into its own function.
A deferred call still runs after `recover`
the remaining defers in that frame continue to execute, so cleanup you registered earlier is not skipped by a panic.