Go — declared and not used / assigned but never used
Resolve Go unused variable errors by using blank identifiers, the blank assignment, or removing dead variables.
Symptoms
- declared and not used: x
- declared and not used: err
- assigned but never used
- The build fails only under the compiler, not in an editor
Possible causes
- A local variable is declared but never read
- An error return is assigned but never checked
- An imported package is unused
- A returned value is captured then ignored with :=
Diagnosis steps
Read which identifier is unused
go build ./...Interpretation
The compiler names the variable, import or value, so you can remove it or use it deliberately.
Use the blank identifier for intentional ignores
_ = err ; _ = someValueInterpretation
Blank assignment marks an intentional discard, satisfying the compiler without introducing a fake use.
Verify the import is needed
goimports -l .Interpretation
goimports adds and removes imports, fixing unused imports and missing ones together.
Root cause
Go treats unused local variables and imports as compile errors to prevent dead code and missed error handling, so a declaration or import that is never used stops the build.
Fix
Remove truly unused declarations and imports, and use the blank identifier for values you intentionally discard, especially error returns that you have chosen to handle differently.
Verify the fix
Build and test again and confirm no unused errors remain, and confirm that removing a value did not drop logic that was actually needed.
Symptom walkthrough
The build fails with declared and not used, assigned but never used, or an unused import message, while an editor may only warn. Go makes these compile errors on purpose: an unchecked error value is a common bug, so the compiler refuses to let a declared variable or import sit idle. The fix is to use it, handle it, or explicitly discard it.
Fix in practice
Remove genuinely dead declarations and imports, and use the blank identifier to discard values you are intentionally ignoring, particularly errors you have decided not to propagate. Treat an unused error variable as a prompt to decide how the error should be handled rather than silencing it.
Verification
Rebuild and run the tests and confirm no unused errors remain, then confirm that removing a declaration did not drop needed behavior. A clean build with unchanged behavior confirms the cleanup was safe.
Diagnostic commands
Check the behavior with commands like these:
go build ./...
_ = err ; _ = someValue
goimports -l .