The defer Statement
In this page:
Basic defer
A defer statement schedules a function call to execute just before the surrounding function returns, regardless of how it returns (including via panic). This is Go's primary tool for guaranteed cleanup code, similar to finally blocks in other languages.
Example: Basic defer
package main
import "fmt"
func greet() {
defer fmt.Println("goodbye")
fmt.Println("hello")
}
func main() {
greet()
}
Login to try C/C++/Java/PHP code in the editor
LIFO Order of Multiple Defers
When a function has several defer statements, they execute in last-in-first-out order: the most recently deferred call runs first. This mirrors how you'd want to unwind a stack of nested resources.
Example: LIFO Order of Multiple Defers
package main
import "fmt"
func main() {
defer fmt.Println("first deferred (runs last)")
defer fmt.Println("second deferred (runs middle)")
defer fmt.Println("third deferred (runs first)")
fmt.Println("main body")
}
Login to try C/C++/Java/PHP code in the editor
Arguments Are Evaluated Immediately
A subtlety of defer is that the arguments to the deferred function are evaluated the moment the defer statement runs, not when the deferred call actually fires later -- only the call itself is postponed.
Note: If you need the latest value at return time, defer a closure instead of a plain function call.
Example: Arguments Are Evaluated Immediately
package main
import "fmt"
func main() {
x := 1
defer fmt.Println("deferred x was:", x) // captures x=1 now
x = 99
fmt.Println("current x:", x)
}
Login to try C/C++/Java/PHP code in the editor
defer for Cleanup
The most common real-world use of defer is guaranteeing that a resource acquired at the start of a function -- a file, a lock, a network connection -- gets released no matter which return path the function takes.
Example: defer for Cleanup
package main
import "fmt"
func process() {
fmt.Println("acquiring resource")
defer fmt.Println("releasing resource")
fmt.Println("using resource")
}
func main() {
process()
}
Login to try C/C++/Java/PHP code in the editor
- Deferring inside a tight loop (e.g. deferring file.Close() for thousands of files in one function) which piles up and delays cleanup until the whole function returns.
- Assuming deferred function arguments are evaluated when the deferred call runs, when they're actually evaluated immediately at the defer statement.
- Expecting multiple defers to run in the order they were written -- they actually run in last-in-first-out (LIFO) order.
- defer schedules a function call to run right before the enclosing function returns.
- Deferred calls run in last-in-first-out order when there are multiple defers.
- Arguments to a deferred call are evaluated immediately, not when the deferred call actually runs.
- defer is the idiomatic way to guarantee cleanup, like closing a file or unlocking a mutex.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: