How to Use Multiple defer Statements in Go
In Go, you can use multiple
defer statements to delay function calls until the surrounding function returns. These deferred calls execute in last-in, first-out (LIFO) order, meaning the last defer added runs first.Syntax
The defer keyword is used before a function call to delay its execution until the surrounding function finishes. You can write multiple defer statements in one function.
- defer functionCall(): Schedules
functionCall()to run later. - Deferred calls run in reverse order of their appearance.
go
func example() {
defer fmt.Println("First defer")
defer fmt.Println("Second defer")
fmt.Println("Function body")
}Example
This example shows three defer statements. They run in reverse order after the main function body finishes.
go
package main import "fmt" func main() { defer fmt.Println("defer 1") defer fmt.Println("defer 2") defer fmt.Println("defer 3") fmt.Println("main function running") }
Output
main function running
defer 3
defer 2
defer 1
Common Pitfalls
One common mistake is expecting deferred functions to run in the order they appear. They actually run in reverse order (LIFO). Another pitfall is deferring functions that capture variables which may change before the defer runs.
Always remember that deferred calls execute after the surrounding function returns, so variable values might differ if not captured properly.
go
package main import "fmt" func main() { for i := 0; i < 3; i++ { defer fmt.Println(i) // This prints 2, 1, 0 because defer captures i by value at call time } }
Output
2
1
0
Quick Reference
| Concept | Description |
|---|---|
| defer | Delays execution of a function until surrounding function returns |
| Multiple defers | Allowed; execute in last-in, first-out order |
| Variable capture | Deferred functions capture variables at defer statement execution |
| Use cases | Resource cleanup, closing files, unlocking mutexes |
Key Takeaways
Multiple defer statements run in reverse order of their appearance (LIFO).
Deferred functions execute after the surrounding function returns.
Be careful with variable values captured by deferred functions inside loops.
Use defer to simplify cleanup tasks like closing files or releasing locks.