Are for-loop variables in Go not captured as locally assigned closure variables?
No, captured for-loop variables in Go are by default captured as values, not variables. This behavior differs from languages like C#, which requires extra syntax to capture variables instead of values.
Example: Capturing Loop Variables as Values
package main import "fmt" func main() { a := 1 b := func() { fmt.Println(a) } // b captures the value of a, not the variable itself a++ b() // prints 1, not 2 }
In this example, the function b captures the value of a at the time it is defined, rather than retaining a reference to the variable itself. Consequently, any changes made to a after defining b will not be reflected in the value printed by b.
Example: Capturing Loop Variables as Variables
However, it is possible to capture loop variables as variables by using a closure syntax that creates a new scope for each iteration:
package main import "fmt" func main() { a := 1 for a < 10 { b := func() { fmt.Println(a) } // b captures the variable a in a new scope a++ b() // prints 2, 3, 4, ..., 10 } }
In this example, the func keyword is used to create a closure for each iteration of the loop. This technique ensures that each closure captures a unique reference to the loop variable, allowing us to observe the value of a as it changes within the loop.
Conclusion
Go capturaes for-loop variables as values by default, but it also provides a closure syntax that allows for-loop variables to be captured as variables. Understanding this distinction is crucial for avoiding confusion and writing correct and efficient Go code.
The above is the detailed content of Does Go Capture For-Loop Variables as Values or Variables?. For more information, please follow other related articles on the PHP Chinese website!