Understanding Go’s defer: Common Pitfalls and Execution Effects
This article explains how Go's defer statements evaluate arguments, interact with panic, affect return values, and behave with os.Exit, providing clear code examples and conclusions to help developers avoid common mistakes.
Introduction
In previous posts we discussed the usage and implementation of defer in Go, but many developers still encounter pitfalls; this article demonstrates common scenarios with code examples to avoid mistakes.
1: Defer passes arguments by value
func deferTest() {
var a = 1
defer fmt.Println(a)
a = 2
return
}Conclusion: The argument to fmt.Println(a) is evaluated when the defer statement is encountered, so later changes to a do not affect the deferred call.
2: Defer passes arguments by address
func deferTest() {
var arr = [3]int{1, 2, 3}
defer printTest(&arr)
arr[0] = 4
return
}
func printTest(array *[3]int) {
for i := range array {
fmt.Println(array[i])
}
}Conclusion: The address of the array is captured at the defer point; because the deferred function runs before the surrounding function returns, the modified array values are printed.
3: Defer can modify a function's return value
fmt.Println(deferTest)
func deferTest() (result int) {
i := 1
defer func() {
result = 2
}()
return i
}Conclusion: The return process is "set return value → execute defer → return"; the deferred function changes the named return variable, so the final result is 2.
4: Defer must be defined before panic to run
func panicBeforeDefer() {
panic("a")
defer func() {
fmt.Println("b")
}()
}
func panicAfterDefer() {
defer func() {
fmt.Println("b")
}()
panic("a")
}Conclusion: When a panic occurs, the runtime first runs deferred calls (LIFO order) before unwinding, so a defer placed after a panic will still execute.
5: Check error before deferring resource release
func openFile() {
file, err := os.Open("txt")
if err != nil {
return
}
defer file.Close()
}Conclusion: Only defer the close operation after confirming the file was opened successfully; otherwise, deferring on a nil resource could cause a runtime error.
6: Defer is not executed when os.Exit is called
func deferExit() {
defer func() {
fmt.Println("exit")
}()
os.Exit(1)
}Conclusion: os.Exit terminates the program immediately, bypassing deferred calls, unlike panic which still runs defers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
