3 ms·
This is too sneaky and seems like poor form. I'm curious what good use-case there is for this, that the language bothered to support and allow this to even com
by poorform 9y ago
This is too sneaky and seems like poor form.
I'm curious what good use-case there is for this, that the language bothered to support and allow this to even compile.
Duplicate variable name declaration + referencing in the same scope is unintuitive at best, and just seems wrong.
- pcwalton 9y agoShadowing can be useful if you want to make sure the "old" variable is never referenced again in the same scope. The reason why this idiom feels "weird" is that the loop construct of the language really ought to automatically make a fresh instance of the loop counter for each trip through the loop.
- knorker 9y agoI don't feel that it's in more poor form than the solution suggested in the article: for i := 0; i < 3; i++ { defer func(i int) { fmt.Println(i) }(i) } This shadows `i` pretty much the same amount as what I wrote. If `i` gets a different name inside the lambda, then it'd also be worse because then you could accidentally use `i` still.
- tylersmith 9y agoI personally prefer the version presented in the article, but your version has at least one nice feature in that you can cleanly specify at the top of the loop body which variables are being shadowed.