2 ms·
My favorite little annoyance with Go is the way the := operator behaves with multiple assignment. It declares a new variable if there is no variable of that nam
by fauigerzigerk 10y ago
My favorite little annoyance with Go is the way the := operator behaves with multiple assignment. It declares a new variable if there is no variable of that name in the current scope. But it refuses to do that if there are struct fields involved.
var t int
t, err := someFunc() // that's fine
but this doesn't compile:
var s struct{ x int }
s.x, err := someFunc() // doesn't compile
- garfij 10y agoI've run into that as well, but I've since come to favor avoiding that pattern entirely as a code smell. In your example, you end up modifying the struct value x, even if there was an error. Maybe there are cases where that is the correct behavior, but even then I would advocate for explicitly setting the struct value after handling the error, to make it very clear that it was your intention to do so, rather than doing it be accident.