defer in Go

Contents
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

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: