Junior — Middle
Milline on tulem, kui muutuja väärtus määratakse defer-i konstruktsiooni kasutades, kui selle väärtus määratakse funktsiooni sees?
sobes.tech AI
Vastus AI-lt
In Go, the keyword defer postpones the execution of a function until the surrounding function exits. The arguments of the function passed to defer are evaluated immediately at the point of the defer statement, not at the time of execution.
If a variable is used inside the function called via defer, its value will be that at the time of the defer declaration if passed as an argument. If the variable is used directly (for example, through a closure), its current value at the time of execution will be used.
Example:
func example() {
x := 1
defer fmt.Println(x) // x will be 1, as the argument is evaluated immediately
x = 2
}
// When calling example(), it will output: 1
If a closure is used:
func example() {
x := 1
defer func() { fmt.Println(x) }() // the function will be called at exit, x will be 2
x = 2
}
// When calling example(), it will output: 2
Thus, the result of assigning a variable in defer depends on how the variable is used — as a function argument or through a closure.