Home > Article > Backend Development > How Does Go's `defer` Statement Handle Closure Parameters?
In Go, the "defer" statement allows functions to defer the execution of a function call until the surrounding function returns. This behavior can lead to unexpected results when the defer statement captures closure's parameters.
Part 2 vs. Part 3: The Captured Parameter
Consider the following code:
for i := range whatever { defer func() { fmt.Println(i) }() } // part 2 for i := range whatever { defer func(n int) { fmt.Println(n) }(i) } // part 3
Part 2:
In "part 2," the defer statement creates a closure that captures the variable "i." When the closure is executed, the "i" variable has the value it had in the last iteration of the range statement, which is 4. Therefore, the output is "44444."
Part 3:
In "part 3," the defer statement creates a closure that does not capture any outer variables. The closure's "n" parameter is evaluated when the defer statement executes, and it receives the value of "i" at that moment. This results in the desired output of "43210" because each defered function call uses a different value for "n."
Key Points:
Understanding the capture behavior of defer statements is crucial to avoid unexpected results in your Go code.
The above is the detailed content of How Does Go's `defer` Statement Handle Closure Parameters?. For more information, please follow other related articles on the PHP Chinese website!