Go: declared and not used compile error
Go rejects unused local variables and imports on purpose. Delete dead declarations, handle err values and keep imports honest instead of blanking them.

Introduction & Quick Summary
Go refuses to compile code that other languages would accept with a warning:
./main.go:12:2: declared and not used: total
./main.go:4:2: "strings" imported and not usedQuick answer: Go treats unused local variables and unused imports as errors. A variable declared with := or var inside a function must be read somewhere, and every import must be referenced by an identifier.
total := compute() // compile error if total is never read
fmt.Println(total) // now it is usedThis rule is deliberate. It keeps refactors honest and stops dead code from accumulating, and it is why Go has no "unused variable" lint warnings: the compiler itself refuses. The friction appears in three places: variables left behind after an edit, err values that were assigned but never checked, and imports that became unused when a call was removed. This guide covers each, the cases where the rule does not apply, and the shortcuts that are safe.
Core Mechanics, Signatures & Reproducible Setup
The spec requires every declared variable inside a function body to be used, and every import to be used. Package-level variables, constants, types, functions and struct fields may be unused, because they are part of the package's API.
package main
import (
"fmt"
"strings" // unused import: compile error
)
func main() {
var total int // declared and not used
result := 0 // declared and not used
fmt.Println("hi")
}go build ./...
# ./main.go:5:2: "strings" imported and not used
# ./main.go:9:2: declared and not used: total| Declaration | Unused is an error | Why |
|---|---|---|
local variable x := 1 | yes | dead local code |
local var x int | yes | same |
| function parameter | no | part of the signature |
| named return value | no | may be assigned later |
package-level var | no | possibly used by another file |
| struct field | no | reflection and serialisation |
| type and method | no | part of the API |
| import | yes | unused dependency and compile cost |
import with _ | no | side effects only |
import with alias . | no | merged into file scope |
| Error text | Trigger | Fix |
|---|---|---|
declared and not used: x | local never read | use it or delete it |
declared and not used: err | error ignored | handle or log it |
imported and not used: "fmt" | import removed from code | remove the import |
x declared and not used after := | shadowing left outer unused | use the outer variable or delete it |
label defined and not used | goto target removed | delete the label |
no new variables on left side of := | all names already declared | use = for assignment |
Key Comparison Table
| Situation | Safe fix | Unsafe shortcut |
|---|---|---|
| Placeholder during refactor | delete the declaration | _ = x hides it forever |
| Interface satisfaction | var _ Reader = (*File)(nil) | unused local with a comment |
| Import for side effects | import _ "net/http/pprof" | blank identifier on a normal import |
| Ignoring a return value | _ = file.Close() | leaving err unchecked |
| Debug print | fmt.Println then remove both | _ = fmt.Sprint |
| Range index unused | for range items | for i := range plus _ = i |
| Category | Unused allowed | Common mistake |
|---|---|---|
| package level var | yes | assuming it is an error |
| struct field | yes | adding _ = field needlessly |
| function parameter | yes | renaming to _ and losing documentation |
| type parameter | yes | unused generic parameter compiles |
| method | yes | dead method keeps building |
| import | no | forgetting goimports |
| local variable | no | leaving result after a refactor |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Leftovers from a refactor
func sum(values []int) int {
total := 0
// for _, v := range values { total += v } // commented out
return 0
}When the loop is commented out, total becomes unused and the build breaks. Delete the declaration instead of adding _ = total; the blank assignment keeps dead code compiling and hides the real intent. Editors with gopls mark the line and offer a quick fix that removes it.
2. Imports
import (
"encoding/json"
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("config.json")
if err != nil {
panic(err)
}
var cfg map[string]any
if err := json.Unmarshal(data, &cfg); err != nil {
panic(err)
}
fmt.Println(cfg)
}Remove json and the file still compiles until the Unmarshal call remains; remove the Unmarshal and the import becomes an error. goimports and most editors fix this on save. For a deliberate side-effect import, the blank identifier is the correct syntax:
import _ "github.com/lib/pq" // registers the driver3. err values that were never checked
func save(path string, data []byte) {
os.WriteFile(path, data, 0o644) // err ignored: allowed by the compiler
}Ignoring a returned error is legal; declaring err := os.WriteFile(...) and never reading it is not. The compiler nudges toward the right shape:
if err := os.WriteFile(path, data, 0o644); err != nil {
return fmt.Errorf("write %s: %w", path, err)
}This if err := ...; err != nil form is the idiom precisely because it uses the value in the same statement.
4. Shadowing that leaves the outer variable unused
func run() error {
var err error
if ok {
result, err := doWork() // new err shadows the outer one
_ = result
}
return err // always nil
}result, err := doWork() declares a new err in the inner scope, so the outer err is never assigned and may be reported as unused, while the real error is dropped. Fix with a declared result and plain =:
var result string
var err error
if ok {
result, err = doWork()
}
return err5. Range variables
for i := range items { // i unused if only the value is needed
fmt.Println(items[i])
}
for range items { // no variables, no error
count++
}Since Go 1.22 the loop variable is per-iteration, so closures capturing it behave as expected. A common compile error after an edit is an unused index that used to feed a slice access; switching to for range removes both the variable and the error.
6. Build tags, generated code and tools
//go:build tools
package tools
import _ "github.com/golangci/golangci-lint/cmd/golangci-lint"The blank import with a build tag pins a tool version without linking it. Generated files sometimes carry unused imports after regeneration; rerun the generator rather than editing by hand. Use the diff checker to compare a generated file with its previous version, and the JSON formatter when an unused field turns out to be a struct tag mismatch that made a decode silently fail.
Common Compilation/Runtime Mistakes & Version Gotchas
_ = xto silence the compiler. It works and defeats the purpose. If the value is truly unused, delete it.- Thinking all unused identifiers are errors. Package-level declarations, fields, methods, parameters and types are fine; only locals, imports and labels are enforced.
go vetconfusion.vetreports different problems (printf verbs, lost cancels, loop closure capture before 1.22). The unused-variable rule is the compiler's, andgo vetwill not find it.- Test files.
_test.gofiles follow the same rule; a helper assigned to a variable and never used failsgo testcompilation. - Cgo and build tags. A file excluded by a build tag can hold a declaration that another configuration needs; the error appears only for the configuration being built, so check with
go build -tags. - Version notes. Go 1.22 changed loop variable scoping; code that relied on sharing one variable now compiles differently and may produce a new unused-variable error after the rewrite. Go 1.21 added the
slicesandmapspackages, and imports of them are only "unused" when the calls were removed. - Modules versus GOPATH.
GO111MODULE=offbuilds can behave differently around vendor directories, but the unused-import rule is unchanged.
The habit that prevents the error is small and local: run go build ./... or gopls on save, let the tooling delete dead declarations instead of blanking them, and treat every unused err as a bug report rather than a formatting issue.
Official documentation: Effective Go and the Go language specification.
Official references
primary documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.
Go: import cycle not allowed
Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.
Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.