4 ms·
> For example, Go's language guards against unused variables or imports, they are a compiler error. Assigning an `err` variable but not using it is a compiler e
by TheDong 2y ago
> For example, Go's language guards against unused variables or imports, they are a compiler error. Assigning an `err` variable but not using it is a compiler error.
Unfortunately, Go's language design also enables unused variables without any error or warning. They are only sometimes a compiler error.
Specifically, multiple return interacts poorly with unused variable detection. See:
func fallable() (int, error) {
return 0, nil
}
func f1() {
val, err := fallable()
if err != nil { panic(err) }
fmt.Println(val)
val2, err := fallable()
fmt.Println(val2)
// notice how I didn't check 'err' this time? This compiles fine
}
When you use `:=` it assigned a new variable, except when you do multiple return it re-assigns existing variables instead of shadowing them, and so the unused variable check considers them as having been used.
I've seen so many ignored errors from this poor design choice, so it really does happen in practice.