The defer statement schedules a function call to run just before the surrounding function returns. It’s how Go makes sure cleanup happens: files get closed and locks get released, whichever way the function exits. In this lesson you’ll learn exactly when deferred calls run, in what order, the two classic pitfalls, and how panic and recover fit in.
If you know Python’s with statement or try/finally in Java, defer solves the same problem with less ceremony.
Your first defer
Put defer in front of a function call, and Go postpones that call until the function you’re in is about to return:
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}Code language: Go (go)
hello
worldCode language: plaintext (plaintext)
The deferred call runs however the function ends: by reaching the closing brace, by any of several return statements, or by a panic (more on that below). That’s what makes it useful. You write the cleanup once, right next to the setup, and you can’t forget it on some early return:
package main
import "fmt"
func process(n int) string {
fmt.Println("start", n)
defer fmt.Println("cleanup", n)
if n < 0 {
return "negative, giving up"
}
return "done"
}
func main() {
fmt.Println(process(-1))
fmt.Println(process(5))
}Code language: Go (go)
start -1
cleanup -1
negative, giving up
start 5
cleanup 5
doneCode language: plaintext (plaintext)
Notice that “cleanup” prints before the caller prints the returned string. The deferred call runs after the return value is decided, but before control goes back to the caller.
The classic use: closing files
The pattern you’ll see most is: acquire a resource, check the error, defer its release. Here’s a function that creates a temporary file, writes to it and cleans up:
package main
import (
"fmt"
"os"
)
func writeGreeting() error {
f, err := os.CreateTemp("", "greeting-*.txt")
if err != nil {
return err
}
defer os.Remove(f.Name())
defer f.Close()
if _, err := f.WriteString("hello\n"); err != nil {
return err
}
fmt.Println("wrote the greeting")
return nil
}
func main() {
if err := writeGreeting(); err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("all cleaned up")
}Code language: Go (go)
wrote the greeting
all cleaned upCode language: plaintext (plaintext)
Two details matter here. First, the defer comes after the error check: if CreateTemp fails, there’s no file to close. Second, whether WriteString fails or succeeds, both the close and the removal happen. Files get a full lesson in stage 6; the error type is explained in the next lesson.
The same pattern works for anything that must be released. With a mutex, which you’ll meet in the sync lesson, it looks like this:
mu.Lock()
defer mu.Unlock()
// work with the shared dataCode language: Go (go)
Last in, first out
When a function has several deferred calls, they run in reverse order: last in, first out (LIFO), like a stack of plates:
package main
import "fmt"
func main() {
defer fmt.Println("defer 1")
defer fmt.Println("defer 2")
defer fmt.Println("defer 3")
fmt.Println("main body")
}Code language: Go (go)
main body
defer 3
defer 2
defer 1Code language: plaintext (plaintext)
This order is exactly what cleanup needs. Things are torn down in the reverse order they were set up, so a resource is never released while something that depends on it is still in use. In the file example, the file is closed first and removed second.
Arguments are evaluated immediately
Go evaluates the arguments of a deferred call when the defer statement runs, not when the call finally happens. This catches people out:
package main
import "fmt"
func main() {
x := 1
defer fmt.Println("deferred with argument:", x)
defer func() {
fmt.Println("deferred closure sees:", x)
}()
x = 99
fmt.Println("x is now", x)
}Code language: Go (go)
x is now 99
deferred closure sees: 99
deferred with argument: 1Code language: plaintext (plaintext)
The first defer captured the value 1 the moment it ran. The second defers an anonymous function with no arguments; it’s a closure that reads x when it finally runs, so it sees 99. Pick whichever behavior you need: pass arguments to freeze a value, use a closure to see the latest one.
Pitfall: defer in a loop
Deferred calls run when the function returns, not at the end of a loop iteration or a block. Defer inside a loop and the calls pile up:
package main
import "fmt"
func main() {
for i := range 3 {
fmt.Println("open", i)
defer fmt.Println("close", i)
}
fmt.Println("loop finished")
}Code language: Go (go)
open 0
open 1
open 2
loop finished
close 2
close 1
close 0Code language: plaintext (plaintext)
With three prints that’s harmless. With files it’s a real bug: process ten thousand files this way and all ten thousand stay open until the function ends, and your program may run out of file handles. The fix is to move the body of the loop into its own function, so each defer runs at the end of each call:
package main
import "fmt"
func handle(i int) {
fmt.Println("open", i)
defer fmt.Println("close", i)
fmt.Println("work", i)
}
func main() {
for i := range 3 {
handle(i)
}
fmt.Println("loop finished")
}Code language: Go (go)
open 0
work 0
close 0
open 1
work 1
close 1
open 2
work 2
close 2
loop finishedCode language: plaintext (plaintext)
Changing a return value with defer
A deferred closure runs after the return statement has set the results, and it can still change them, but only if the results are named. Here’s the mechanism in its simplest form:
package main
import "fmt"
func answer() (n int) {
defer func() {
n *= 2
}()
return 21
}
func main() {
fmt.Println(answer())
}Code language: Go (go)
42Code language: plaintext (plaintext)
return 21 sets n to 21, then the deferred closure doubles it, then the function returns. You won’t double numbers like this in real code, but the same trick is genuinely useful when the cleanup itself can fail. Closing a file you’ve written to can report an error (the data might not have been flushed to disk), and with a named err result you can pass that error on instead of losing it:
package main
import (
"fmt"
"os"
)
func save(path, text string) (err error) {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
if closeErr := f.Close(); closeErr != nil && err == nil {
err = closeErr
}
}()
_, err = f.WriteString(text)
return err
}
func main() {
path := os.TempDir() + "/defer-demo.txt"
defer os.Remove(path)
if err := save(path, "saved\n"); err != nil {
fmt.Println("error:", err)
return
}
data, _ := os.ReadFile(path)
fmt.Print(string(data))
}Code language: Go (go)
savedCode language: plaintext (plaintext)
The closure only overwrites err when nothing else failed first, so the original error wins. Don’t worry if this feels dense now; come back to it after the errors lesson.
panic and recover
A panic is Go’s way of stopping a program that hit something it can’t handle, like indexing past the end of a slice or calling panic("...") yourself. When a function panics, it stops immediately, its deferred calls run, then its caller’s deferred calls run, and so on up the stack. If nothing stops it, the program crashes with the panic message and a stack trace.
The built-in recover stops a panic. It only works when called directly inside a deferred function: there it returns the value the panic was called with, and the function returns normally instead of crashing. Anywhere else, recover returns nil and does nothing.
package main
import "fmt"
func safeIndex(items []string, i int) (item string) {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
item = "(none)"
}
}()
return items[i]
}
func main() {
colors := []string{"red", "green", "blue"}
fmt.Println(safeIndex(colors, 1))
fmt.Println(safeIndex(colors, 5))
fmt.Println("program keeps running")
}Code language: Go (go)
green
recovered: runtime error: index out of range [5] with length 3
(none)
program keeps runningCode language: plaintext (plaintext)
This example shows how recover works; it’s not how you should write Go. Ordinary failures (a missing file, bad input, a network error) are reported by returning an error, and the caller decides what to do. A panic means a bug or a truly impossible situation. Checking i < len(items) first would be the right fix here.
Where is recover legitimately used? Mostly at boundaries, where one failure shouldn’t take everything down. Go’s HTTP server, for example, recovers a panic in one request handler so the other requests keep working. In your own code you’ll rarely need it. One more thing to know: os.Exit ends the program immediately and does not run deferred calls. The Go blog’s Defer, Panic, and Recover goes deeper if you’re curious.
Practice
1. Predict the output. Before running it, write down what this program prints. Then check.
package main
import "fmt"
func main() {
for i := range 3 {
defer fmt.Print(i, " ")
}
n := 10
defer fmt.Println("n =", n)
n++
fmt.Print("go: ")
}Code language: Go (go)
Show the answer
go: n = 10
2 1 0Code language: plaintext (plaintext)
"go: " prints first because everything else is deferred. Then the defers run last in, first out: the Println with n was deferred last, so it runs first, and it prints 10 because its argument was evaluated before n++. Finally the loop’s three defers run in reverse: 2, 1, 0.
2. A tracing helper. Write a function trace(name string) func() that prints enter plus the name and returns a function that prints exit plus the name. Use it as defer trace("work")() at the top of a function work that calls another traced function step. Why are there two pairs of parentheses?
Show a solution
package main
import "fmt"
func trace(name string) func() {
fmt.Println("enter", name)
return func() {
fmt.Println("exit", name)
}
}
func step() {
defer trace("step")()
fmt.Println(" doing the step")
}
func work() {
defer trace("work")()
step()
}
func main() {
work()
}Code language: Go (go)
enter work
enter step
doing the step
exit step
exit workCode language: plaintext (plaintext)
trace("work") is the “argument” part of the deferred call, so it’s evaluated right away and prints enter work. The second () is the call that gets deferred: the returned function, which prints exit work when work returns.
Key takeaways
- A deferred call runs when the surrounding function returns, whether by
return, by reaching the end, or by a panic. - Multiple defers run last in, first out. Defer the cleanup right after the error check for the setup.
- Arguments are evaluated when the
deferstatement runs; a deferred closure sees the latest values. - Don’t defer inside a long loop; move the loop body into its own function.
- With named results, a deferred closure can change the return value.
recoveronly works inside a deferred function, and ordinary code returns errors instead of panicking.