3 ms·
In my experience, the multiple-return `, err` convention and the `:=` syntax sugar are constantly clashing. It's confusing because the `err` is reused, but stil
by NoodleIncident 7y ago
In 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