defer in Go
| defer runs LIFO | |
| defer Close() everywhere | |
| Arguments evaluate now | |
| Trace with defer |
defer runs LIFO
Deferred calls wait until the surrounding function returns, then run last in, first out. Read the defers bottom up to see the true cleanup order.
package main
import "fmt"
func main() {
defer fmt.Println(1)
defer fmt.Println(2)
defer fmt.Println(3)
fmt.Println("body")
}
body
3
2
1
The body prints first, while the three deferred calls fire in reverse after main returns. This stack order pairs nested setup and teardown naturally: the last thing acquired is the first thing released.
defer Close() everywhere
Open resources beg for a deferred Close on the very next line. Files, response bodies, and locks all leak when an early return skips cleanup, but a defer runs on every path out of the function.
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Create("notes.txt")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
fmt.Fprintln(f, "remember defer")
fmt.Println("written")
}
Check the error first, then defer the Close immediately so no later edit can strand the file open. The same habit guards mutex Unlock calls and database transaction rollbacks.
Arguments evaluate now
The function value and its arguments are fixed at the moment defer runs, not when the call finally executes. This surprises newcomers in loops and counters, so capture changing values explicitly when the order matters.
package main
import "fmt"
func main() {
x := 1
defer fmt.Println(x)
x = 2
fmt.Println(x)
}
2
1
The deferred Println remembers 1, the value x held when defer executed, while the body prints the updated 2. A closure would see the variable instead: defer func() { fmt.Println(x) }() prints 2 twice, because it reads x late.
Trace with defer
Pair an entry print with a deferred exit print to trace slow or tangled code. The returned closure runs at function end, so exits appear even when the middle returns early.
package main
import "fmt"
func traced(name string) func() {
fmt.Println("enter", name)
return func() {
fmt.Println("exit", name)
}
}
func work() {
defer traced("work")()
fmt.Println("working")
}
func main() {
work()
}
The traced call prints enter at once and hands back a closure that defer holds until work ends. Sprinkle this helper across suspect functions, read the nested log, then remove it once the mystery is solved.
Next: Strings, bytes and runes
Article author: Arthur Isaev