Hacker News new | ask | show | jobs
by Matthias247 3567 days ago
It's really a common source of error, I was hit by it once and lots of other people too. However It's not only common to Go, I learned that behavior in C# (which captured loop variables by reference), which I think they changed in the meantime. It can be also encountered in Javascript (if a var instead of let binding is used for the loop variable).

I found it interesting that the old Java style guarded against that behavior, because it required captured things to be final, so you had to copy the thing you wanted to capture from the loop variable into a fresh final variable anyway.

The good thing is: If you encounter this behavior once in any programming language you most likely research in new ones how loop variables interact with closures. So the golang behavior wasn't a new source of errors for me.

However I still learned something new here: I didn't expect the different behavior between the go/defer statement() and go/defer func() {statement()}() variants.