Sobes.tech
Junior — Middle

What happens to the function arguments passed to defer when it is executed?

sobes.tech AI

Answer from AI

In Go, when using defer, the arguments of the function passed to defer are evaluated immediately at the moment of the defer statement, while the function itself is called later, when the surrounding function completes.

This means that if the arguments are modified after the defer, the deferred call will use exactly the value that was at the moment of the defer.

Example:

func example() {
    x := 10
    defer fmt.Println(x) // argument x is fixed as 10
    x = 20
}
// When exiting example, 10 will be printed, not 20

Thus, defer saves copies of arguments at the time of declaration.