GO SECRET
Go Secret — Defer: What you know about DEFER in Go is not enough!
This article looks at some not-so-obvious things about the “defer” statement in Go, showing you a few things you might not know.
4 min readJan 8, 2023
Hey, you think you know everything there is about ‘defer’? Well, think twice.
Believe me, it’s not just about postponing a function’s execution until your current function wraps up. Whether you’re new to Go or an old hand, this guide has something valuable for you.
So, let’s get started.
1. Evaluating Arguments
Have you ever realized that the arguments for a deferred function in Go are actually set when you first hit the defer statement, not when the deferred function finally runs?
Check out this example for clarity:
package main
import "fmt"
func main() {
i := 0
defer fmt.Println(i)
i++
}
So, what do you think will pop up in the console?
Even though fmt.Println(i)
only fires off at the end, after i
is incremented to 1, it still outputs 0. Weird, isn't it?