4 ms·
In most cases the reference is hidden in the context of a lexical closure. And arguably it's not about unexpected mutability, but the context of mutability. Nob
by wahern 3y ago
In most cases the reference is hidden in the context of a lexical closure. And arguably it's not about unexpected mutability, but the context of mutability. Nobody is expecting `i' to be immutable, but in the context of a for loop its demonstrably the case that most people intuitively expect `i' to be scoped to the inner block and not the looping statement itself; and that intuition is so strong that even people who thoroughly understand the implementation details still sometimes run afoul of the issue when mechanically banging out code.
One can disagree with the wisdom of lexical closures, as opposed to other languages which require explicit declarations when binding variables or capturing values, but ultimately it's a tradeoff and lexical closures are a key architectural construct in Go. In this case, the implementation details resulted in poor cost/benefit, and tweaking the semantics of loop variables restores the cost/benefit in the context of Go's calculus.