Go - (Kinda) Breaking the Compatibility Promise

The Go team is considering making loop variables defined per-iteration rather than per-loop. This is something done in ECMAScript via the const and let variable declaration syntax (as opposed to var). Interestingly, the consensus appears to be that this change fixes significantly more code than it breaks, so they want to move forward with it.

Example:

var prints []func()
for _, v := range []int{1, 2, 3} {
	prints = append(prints, func() { fmt.Println(v) })
}
for _, print := range prints {
	print() // prints 3, 3, 3 presently; should probably print 1, 2, 3
}
1 Like

thanks for sharing, I think this change is for the better, because it fixes a bug or I can also say an UB, I think this will perhaps cause a small set of apps to change code but it will fix a lot more. And folks who are using it in right way are already unaffected. If needed go modules have versions so lock them appropriately and take your time to move to new semantics.

2 Likes

I agree 100%. I found this interesting since the Go team seems much more hesitant to break the compatibility promise than others. This shows that they are willing to bend the rules a bit to help the “greater good.” Good stuff.

1 Like