Sobes.tech
Senior

When are the arguments of deferred functions calculated — at the moment of definition or at the moment of calling the function?

sobes.tech AI

Answer from AI

In Go, the arguments of deferred functions are evaluated at the moment the defer statement is executed, that is, at the point of declaration, not at the moment the deferred function is called. This means that the argument values are fixed immediately, and the function itself is called later.

Example:

package main
import "fmt"

func main() {
    x := 10
    defer fmt.Println(x) // x will be evaluated now, equal to 10
    x = 20
}

The output will be 10, because the argument x for fmt.Println is captured at the moment of defer, not at the time of the call.

When are the arguments of deferred functions… - sobes.tech