Senior
When are the arguments of deferred functions evaluated?
sobes.tech AI
Answer from AI
In Go, the arguments of functions called with defer are evaluated immediately at the moment of the defer statement, but the function itself is called later, when the surrounding function completes.
This means that the argument values are fixed at the time of the defer call, not at the actual execution of the deferred function.
Example:
func main() {
x := 10
defer fmt.Println(x) // argument x is evaluated here, x=10
x = 20
}
// When executed, it will print 10, not 20
Thus, defer saves the argument values at the moment of declaration, which is important to consider when working with mutable variables.