Go compile error: imported and not used
Fix the Go compiler error "imported and not used" by referencing, aligning, or blank-importing packages that were added but never referenced in code.
Symptoms
- build failed: imported and not used: "fmt"
- go run refuses to start after a refactor removed the last use of a package
- goimports adds imports that the build then rejects
Possible causes
- A package was imported during development but its last use was deleted
- Only a side-effecting import is needed, but the named import form was used
- An alias was added to resolve a name clash and the original import is now dead
- A conditional build tag excludes the only file that used the package
Diagnosis steps
Read the exact import path the compiler names
Interpretation
The error lists the unused package; check whether any remaining identifier from it is referenced anywhere in the file.
Compare imports against actual uses per file
go build ./... 2>&1 | grep "imported and not used"Interpretation
Each reported file has an import with no matching selector; Go enforces unused imports per file.
Decide whether the import is for side effects
Interpretation
Driver and pprof imports are used for their init() side effects and must be blank-imported.
Root cause
Go requires every imported package to be used, because unused imports indicate dead code and slow compilation. The check is per file: an import counts as used only if some selector from it appears in that same file, even if other files in the package use the package.
Fix
Remove imports whose use was deleted, or reference the needed identifier. For side-effect-only imports such as database drivers or net/http/pprof, use a blank import: `import _ "github.com/lib/pq"`. For alias-related dead imports, delete the alias and fix the remaining references.
Verify the fix
Run `go build ./...` and `go vet ./...`; both complete without the unused-import error, indicating all imports resolve to real uses.
Symptoms
The build stops with imported and not used: "fmt" even though the package is clearly referenced elsewhere in the project. The error is reported per file, so the offending import is in a specific file rather than the package as a whole.
Diagnosis
Grep each reported file for a selector of the package:
go build ./... 2>&1 | grep "imported and not used"
If the file imports fmt but never calls fmt., the import is dead. A conditional build tag can also make the only using file invisible to the current build.
Fix
Delete the dead import, or blank-import packages kept for side effects:
import (
_ "github.com/lib/pq" // registers the driver via init()
"fmt"
)
Also run goimports so unused imports are removed automatically.
Verification
go build ./... and go vet ./... both succeed, proving every import has a real use in its file and the package compiles cleanly across the module.