3 ms·
I've been doing quite a bit of Go programming for a while now, and I've internalized all these behaviors, but this one gets me every time: var err error
by oppositelock 10y ago
I've been doing quite a bit of Go programming for a while now, and I've internalized all these behaviors, but this one gets me every time:
var err error
if true {
foo, err := someFunction()
// err gets shadowed
}
It's particularly annoying because if both foo and err are defined in the outer scope, you get a compiler error that no new variables are on the left, so you tend to forget that removing one shadows the other.
- lopatin 10y agoI tend to simply not have duplicate variable names (with the exception of `err`, which is always treated with special care anyways) so this shadowing behavior doesn't really trip me up any more.
- kyrra 10y agoNot sure it would help you but adding "go vet -shadow" to some kind of test or build script may help you detect these problems. https://golang.org/cmd/vet/ https://golang.org/cmd/vet/
- leetrout 10y agoThis. If anyone is using VIM or Atom please please please install the Go helpers, too. Atom's go-plus is awesome. The team I work with- I beg them to use linters and go-plus and avoid these pitfalls like shadowing err. Instead most of them will run the linter, not fix the errors, then defend poor practices like shadowing and returning private types from exported methods.
- omginternets 10y agoI think Go is one of those languages that really benefits from an editor that performs static analysis. I use Atom and go-metalinter catches this on a daily (if not hourly) basis. Variable shadowing is a sharp edge of the language that's very effectively dulled by proper tooling.
- paulsutter 10y agoDeclaration assignments should be more explicit. For example: foo, err ::= someFunction() // explicitly declare both foo, err := someFunction() // declare only foo, err must exist Then you get all the convenience without surprises.