go: declared and not used

Ankur Raina

--

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response