Golang defer Statements in 5 Minutes
Go's defer statement for beginners, in five minutes, on a real Go program: when a deferred call runs (every way out of the function, early returns included), why several run last-in first-out, why a deferred call's values are saved on the defer line, and why defer f.Close() inside a long loop crashes with 'too many open files' until each file gets its own small function.
Two thousand logs, one crash
Your Go program says too many open files, even though you defer closing every file right after you open it. Rich's Go program reads two thousand daily watering logs from his vegetable patch, and it dies at file one thousand and nineteen. So why didn't defer close them? Defer tells Go to run a call later, when the function finishes, and that word later is what bit Rich. In about three minutes you'll see how, and the fix is one small function.
sed -n '14,21p' main.gofor i, name := range files { f, err := os.Open(name) if err != nil { fmt.Printf("file %d of %d: %v\n", i+1, len(files), err) os.Exit(1) } defer f.Close() total += sum(f)
go run .file 1019 of 2000: open readings/day-1019.log: too many open files exit status 1
When a deferred call runs
So when exactly is later? Take Rich's water valves. His program opens the valve for each bed, and right after, he writes defer and the call that closes it. Here it just prints a line, so we can see when it runs. Defer doesn't run that call now. It sets it aside until the function returns. Bed one gets watered, then the valve closes. Bed two is already wet, so Rich's code returns early and skips the watering line, but the valve still closes. Whichever way the function leaves, the deferred call runs.
sed -n '5,12p' main.gofunc water(bed string, wet bool) { fmt.Println("valve open:", bed) defer fmt.Println("valve closed:", bed) if wet { fmt.Println(bed, "is already wet, stop early") return } fmt.Println("watering", bed)
go run .valve open: bed 1 watering bed 1 valve closed: bed 1 valve open: bed 2 bed 2 is already wet, stop early valve closed: bed 2
Even a crash counts as a way out. Bed three's soil sensor sent only two readings. Go counts from zero, so reading number two is the third one, and there isn't one. Go stops with a panic, its word for a crash: index out of range. But look just above the panic message: the words valve closed were printed first, so the beds don't flood while the program falls over.
sed -n '5,8p' main.gofunc water(bed string, readings []int) { fmt.Println("valve open:", bed) defer fmt.Println("valve closed:", bed) fmt.Println("moisture:", readings[2])
go run .valve open: bed 3 valve closed: bed 3 panic: runtime error: index out of range [2] with length 2 goroutine 1 [running]: main.water({0xb018c, 0x5}, {0xf042750e88, 0x2, 0xf042750e98?}) /home/rich/patch/main.go:8 +0x140 main.main() /home/rich/patch/main.go:12 +0x40 exit status 2
Picture a receipt spike by the garden shed door. Each time Rich defers something, he spears a note on it. When the function leaves, he pulls the notes off, top first. So the last thing deferred runs first.

Rich opens valves A, B and C, deferring each close. Watering finishes, and the valves close in reverse: C first, then B, then A. That's usually what you want. Water flows from A to B to C, so you shut the far end first.
go run .open valve A open valve B open valve C watering done close valve C close valve B close valve A
Go's specification, the language's official rulebook, backs up both things we just saw. A deferred call runs when the surrounding function returns, even if it panics. And the calls run in the reverse order they were deferred. But look at the highlighted sentence: whatever you pass to the deferred call is saved when the defer line runs, not when the call finally happens.

The value is saved at once
Here's a defer bug that doesn't crash. It just quietly prints the wrong number. Rich wants a total of the water he used. He starts a litres counter at zero, defers printing it, then waters two beds: twelve litres and thirty. Guess first: zero or forty-two? Zero. The print saved the counter's value when the defer line ran, before any water went out.
sed -n '6,9p' main.golitres := 0 defer fmt.Println("litres used:", litres) litres += 12 // bed 1 litres += 30 // bed 2
go run .watering done litres used: 0
To read the counter at the end, defer a small unnamed function. Write the word func, put your code in curly braces, then add an empty pair of round brackets. Those empty brackets mean call this function. Because defer comes first, Go doesn't call it now. It waits until the way out. Nothing is passed in, so nothing is saved on the defer line. The code inside reads the counter then, and by then it's forty-two.
sed -n '7,9p' main.godefer func() { fmt.Println("litres used:", litres) }()
go run .watering done litres used: 42
Why the loop ran out of files
Now Rich's crash. Defer waits for the function to return, and his loop is inside main, the function every Go program starts in. Each pass opens a log and spears another close, but main never returns while it's looping. So every close stays on the spike, and every file stays open. His laptop, like most Linux machines, lets one program hold about a thousand open files at once. A handful of those are already in use when the program starts, so Rich runs out at file one thousand and nineteen.

The fix: move the work for one file into its own small function, called readLog. Now the defer belongs to readLog, and it runs every time readLog returns, once per file.

Here's readLog. It opens the file, and checks the error first. If the error isn't nil, Go's word for nothing, the open failed, and there's nothing to close. Only then, on the very next line, it defers the close. That's the usual Go habit. Each call opens one file and closes it before the next one starts, so only one log is open at a time. Run it again, and all two thousand logs are read.
sed -n '26,33p' main.gofunc readLog(name string) (int, error) { f, err := os.Open(name) if err != nil { return 0, err } defer f.Close() return sum(f), nil }
go run .files read: 2000 litres: 20000
Recap
So: defer runs a call when the function returns, by any way out. The last one deferred runs first. Its values are saved on the defer line. And in a loop, give each pass its own function.

If defer finally clicked, a like helps YouTube show this to more beginners, and subscribing brings the next Go idiom: interfaces.
All the lab files and commands are linked in the description. Thanks for watching Cloud Explainers.
Sources
Demos: one container on our own Mac standing in for a laptop; the vegetable patch and its logs are made up. Every command, output and number was real. Watch the full video on YouTube.