3 ms·
>isn't even a warning This is actually enforced [in some cases] as a compile-time error. (BTW the `gc` family of Go compilers don't have warnings.) The two er
by drbawb 13y ago
>isn't even a warning
This is actually enforced [in some cases] as a compile-time error. (BTW the `gc` family of Go compilers don't have warnings.)
The two errors in particular that help trap this are:
1. All declared variables must be used.
2. All return values must be assigned to a variable.
(Go allows for multiple return values from a function.)
---
Idiomatically one would store [one or more] return values from a function with a short-form declaration (`:=`) which declares and assigns the LHS to the RHS.
`a,err := someFunc()` where `someFunc()` returns `(SomeType, error)` declares and assigns `a int` and `err error`.
If you declare `a,err := someFunc()` and do not use `a` or `err` elsewhere in scope, your program simply won't compile.
The only way to squelch that error is to either use the variables OR you can use a `_` on the LHS. (Which makes an "assignment" to a blank identifier, e.g: discards the value.)
---
An example of where this _wouldn't_ be enforced by the compiler is if you've declared [and used] `err` elsewhere in the scope and you are _reusing_ the identifier.
For e.g: if you declared, assigned, used, and reassigned `err`. The compiler won't force you to use it _after_ the second assignment, so that second assignment could go untrapped with no complains from the compiler.