Defer pitfalls
suggest changeWhen using defer keep the following in mind: deferred functions are called at the end of a function.
Deferred statements have a function scope, not a block scope.
In other words: deferred calls are executed when exiting a function not when executing block created with if or for statements.
func main() {
fmt.Print("Before if\n")
if true {
defer fmt.Print("inside if\n")
}
fmt.Print("After if\n")
}
Before if
After if
inside if
You might expect that deferred statement to be executed when we exit if branch but it’s executed as the last thing in a function.
Using outside variables in defer functions
func main() {
for i := 0; i < 2; i++ {
defer func() {
fmt.Printf("%d\n", i)
}()
}
}
1
0
Deferred calls run in last-in, first-out order, so this prints 1 and then 0.
For a loop variable declared by the for statement, Go 1.22 and later create a
new variable for each iteration. Each closure therefore captures that iteration's
value.
This is equivalent to creating distinct variables for the iterations and then running the deferred calls in reverse order:
defer fmt.Printf("%d\n", 0)
defer fmt.Printf("%d\n", 1)
Passing the value as a parameter also makes the capture explicit and works with older Go language versions:
func main() {
for i := 0; i < 2; i++ {
defer func(i2 int) {
fmt.Printf("%d\n", i2)
}(i)
}
}
1
0
If a loop reuses a variable declared outside the loop, its closures still capture that one shared variable. Pass it as a parameter when each closure must retain a different value.