defer, order and named results
A deferred call runs when the surrounding function returns, on every path out: a normal return, a return with an error, and a panic unwinding the stack. It is the tool for cleanup that must not be forgotten, and its two rules, last in first out and arguments evaluated at the defer, are the source of both its usefulness and its surprises. The errors lesson returns errors; defer is how a function releases what it acquired before it does.
Last in, first out
Deferred calls form a stack: the last one written runs first. The arguments are evaluated where the defer statement is, not where the call happens, so defer fmt.Println("captured x:", x) prints the value x had at that line. This is what makes a defer cheap to reason about: the values it will use are fixed when it is registered.
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
defer fmt.Println("defer", i)
}
x := 10
defer fmt.Println("captured x:", x)
x = 20
fmt.Println("body done, x =", x)
}
go run order.go
body done, x = 20
captured x: 10
defer 3
defer 2
defer 1
The body printed 20 and the deferred call printed 10, because the argument was copied at the defer. The three loop defers ran in reverse, so the output reads 3, 2, 1: a stack of cleanups unwinds in the order that matches nested resources.
A closure reads late
A deferred function literal is not called at the defer; its body runs at return, so it reads the variables it closes over as they are then. That is the way to capture the final value, and the way to get a surprise when the final value is not what the author meant. A plain function call and a closure therefore differ even when they name the same variable.
package main
import "fmt"
func main() {
msg := "start"
defer func() {
fmt.Println("deferred closure sees:", msg)
}()
defer fmt.Println("plain call sees:", msg)
msg = "end"
fmt.Println("main sees:", msg)
}
go run closure.go
main sees: end
plain call sees: start
deferred closure sees: end
The plain call printed start and the closure printed end. Both are deferred, so the closure ran first; the output order alone shows which one read its argument early. A deferred closure is also how a function logs its result or changes a named return.
Named results are still writable
A deferred function can change a named result, because the result variables are ordinary variables of the function. The common use is an error: a deferred cleanup sets or wraps the error it finds, so the caller sees the failure even though the return statement named nil. Without named results the defer could only print.
package main
import (
"errors"
"fmt"
)
func div(a, b int) (q int, err error) {
defer func() {
if err != nil {
q = -1
}
}()
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
fmt.Println(div(9, 3))
fmt.Println(div(1, 0))
}
go run named.go
3 <nil>
-1 division by zero
The second call returned -1 with the error, because the defer saw a non-nil err and changed q after the return statement had assigned it. The technique is legitimate and easy to overuse: a reader must know that a deferred function can rewrite the result, so keep it close to the signature it changes.
defer inside a loop
A defer registered in a loop runs when the function returns, not at the end of the iteration, so a loop over a thousand items holds a thousand deferred calls and a thousand open resources until the end. The fix is a function per iteration, so each defer runs at the end of its own call, or an explicit close. The compiler has made defer cheap, but cheap is not free at a million iterations.
package main
import "fmt"
func process(items []string) {
for _, item := range items {
defer fmt.Println("closing", item)
}
fmt.Println("function body finished")
}
func main() {
process([]string{"a", "b", "c"})
fmt.Println("back in main")
}
go run loop.go
function body finished
closing c
closing b
closing a
back in main
The three closes ran after the body finished, in reverse, which is the whole problem in miniature. The pattern that scales is defer f.Close() immediately after the error check inside a short function, with the loop calling that function once per item.
Exercises
- Write a function with two defers that print their argument and one that changes a named error. Predict the output before running it.
- Wrap a loop that opens three files in a helper function so each file is closed at the end of its iteration. What changes in the peak number of open files?
- Move a defer fmt.Println(x) above and below the line that changes x. Explain the difference with the rule about arguments.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When does a deferred call run?
Answer
When the surrounding function returns, on every path out
defer is tied to the function, not to the block or the statement.
-
What does this program print?
package main import "fmt" func main() { for i := 1; i <= 3; i++ { defer fmt.Println("defer", i) } x := 10 defer fmt.Println("captured x:", x) x = 20 fmt.Println("body done, x =", x) }Answer
body done, x = 20 / captured x: 10 / defer 3 / defer 2 / defer 1
Defers run last in first out, and the argument was captured at the defer line, before x changed.
-
What does a deferred closure see?
Answer
The values the variables have when it runs
A closure reads the variables at call time; a plain call captured its arguments earlier.
-
What does this program print?
package main import "fmt" func main() { msg := "start" defer func() { fmt.Println("deferred closure sees:", msg) }() defer fmt.Println("plain call sees:", msg) msg = "end" fmt.Println("main sees:", msg) }Answer
main sees: end / plain call sees: start / deferred closure sees: end
The closure is the later defer, so it runs first and reads end; the plain call kept start.
-
What makes a named result changeable from a defer?
Answer
The result variables are ordinary variables of the function
A deferred function can assign to them before the caller receives the values.
-
What does the second line of this program print?
package main import ( "errors" "fmt" ) func div(a, b int) (q int, err error) { defer func() { if err != nil { q = -1 } }() if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { fmt.Println(div(9, 3)) fmt.Println(div(1, 0)) }Answer
3 <nil> / -1 division by zero
The defer saw the error and set the named result to -1.
-
Why is defer inside a loop a problem?
Answer
All the deferred calls run when the function returns, holding every resource until then
A defer per iteration only helps when the iteration is its own function.
-
What does this program print?
package main import "fmt" func process(items []string) { for _, item := range items { defer fmt.Println("closing", item) } fmt.Println("function body finished") } func main() { process([]string{"a", "b", "c"}) fmt.Println("back in main") }Answer
function body finished / closing c / closing b / closing a / back in main
The deferred closes waited for the end of process and then ran in reverse.
-
Where does defer f.Close() belong in a function that opens a file?
Answer
Right after the error check for the open call
After the check the file is non-nil, and the defer is registered on every path that follows.
-
Which cleanup is not a good fit for defer?
Answer
A resource that must be released at the end of each loop iteration
The end of an iteration is not the end of a function, so a helper function or an explicit close is used.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev