3 ms·
It is spot on observation about rather bad rules in Go about := and scopes that hit me as well. For example, the following compiles without warnings and even ru
by fpoling 11y ago
It is spot on observation about rather bad rules in Go about := and scopes that hit me as well. For example, the following compiles without warnings and even runs the first invocation of test successfully, https://play.golang.org/p/tYQSNjudGT https://play.golang.org/p/tYQSNjudGT :
package main
func test(n int) {
for {
n := n - 1;
if n == 0 {
break
}
}
}
func main() {
test(1);
test(2)
}
- kyrra 11y agoThe 'go vet' command has a -shadow flag to check for this. And as the author points out, editors can point it out as well. It definitely isn't ideal, but it can be dealt with. I believe Rob Pike had called out that the number of ways you can do variable assignment/declaration is something he disliked, but it's impossible to change in Go 1 at this point.
- Veedrac 11y agoThat seems somewhat natural to me, to be honest. The same could happen in Rust, or most languages with shadowing. IMO, allowing it is the lesser evil.
- fpoling 11y agoThe issue here is not shadowing in general but shadowing withing a single statement like in n := n + 2. A sane rule would not allow to refer to the declared name in the right-hand side expression.