go: declared and not used
This short article touches a confusing error that you may see while working with Go code.
Easy Case: variable not used at all
As the error itself suggests, you have declared a variable but not used it. The below snippet would result in the error. The fix is to actually use this variable somewhere or just get rid of it.
$ go run main.go
# command-line-arguments
./main.go:.:.: foo declared and not used
Edge Case: variable used but still the same error
Sometimes, the same error may appear when you have actually used the variable in your code. This is due to accidental re-declaration of the same variable in your code in a different scope.
In the following code, you’ll see the same error though the variable has actually been used.
$ go run main.go
# command-line-arguments
./main.go:.:.: foo declared and not used
In the case above, the assignment in line 5 should use =
instead of :=
otherwise, variable foo
is re-declared in the if
block. Since this is a new variable, Go expects it to be used somewhere and hence the error. However, our intention in the first place was not to redeclare it but assign a value instead. So, we change it to the following code which works.
$ go run main.go
Hello
This is sometimes difficult to identify in a bigger code block particularly when you’re expecting multiple values from a function. In such cases, you should ensure that you’re declaring such variables in advance for that scope instead of relying on :=
. The example below should clarify my point.
Thanks for reading!