3 ms·
Java has never had this problem with variables (either in a for loop or free-floating ones), since Java has never had support for closures. There is one somewh
by simiones 3y ago
Java has never had this problem with variables (either in a for loop or free-floating ones), since Java has never had support for closures.
There is one somewhat similar problem in Java that you're maybe thinking of: anonymous classes that reference fields of the current object. I don't think that behavior is surprising, and there are very important use cases for it.
What Go is doing is perfectly sensible. The ability to capture variables is extremely powerful, and often desired. It's just the unexpected scoping of loop variables that introduces a problem. The following code is doing exactly what most people would expect, for example:
a := 0
incr := func() {a += 1}
print := func() {fmt.Printf("%d", a)}
print() // prints 0
incr()
print() //prints 1