5 ms·
> 2. The ':=' assignment with inference operator has sometimes led to unintended variable shadowing. I've been bitten by this once or twice? It is helpful for
by omegabravo 7y ago
> 2. The ':=' assignment with inference operator has sometimes led to unintended variable shadowing.
I've been bitten by this once or twice? It is helpful for when declare and assign multiple return values.
eg:
g, ctx := errgroup.WithContext(ctx)
there is of course a shadowed variable above. In practice it hasn't really been an issue for me, but I can see the foot gun.
The thing I like most about Go is the resulting output is a lot easier to follow. Maybe that's just because I am more familiar with Go than Java. Java seems to have endless abstractions that are not intuitive to me
- NoodleIncident 7y agoIn my experience, the multiple-return `, err` convention and the `:=` syntax sugar are constantly clashing. It's confusing because the `err` is reused, but still has to be created at some point; and because `:=` is allowed even if only one variable is being created, but forbidden if you're only assigning. It doesn't always lead to a bug, but it's always frustrating. Even when restricting the problem to a single (non-error) return value, there are 6 combinations to consider: * What do you do with the non-error return value? (none/assign/create) * Is it the first time you've checked an error? (yes/no) none, yes | err := f() none, no | err = f() assign, yes | var err error; r, err = f() assign, no | r, err = f() create, yes | r, err := f() create, no | r, err := f() The shadowing case comes up infrequently enough to surprise you when it does. You've been trained by the other examples to change `=` to `:=` when you see a certain error, and you don't always get a warning about the shadow this creates.
- irq-1 7y agoThis is annoying and should be fixed: err should be pre-declared along with the stack. := should both allow assignment without creation and NOT create shadow variables (which could still be made explicitly with var.) It would be a poor argument that var and := show where declaration happens. The := rules seem made for the clarity of the parser rather than the programmer.
- NoodleIncident 7y agoThose changes would break existing code, so I don't think they'll go for that. I'm slightly hopeful that whatever Go 2 does for error handling will dodge this issue by not making you declare and re-use the `err` variable, but I don't remember enough about that proposal to tell if it would actually help. In general, the trend of making things easier for the compiler rather than the developer is a thing that annoys me about go, you're right to point that out