Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#go#compiler-errors#refactoring#build
Bold white headline reading UNUSED beside a cyan Go crate holding an amber unused variable chip.

Introduction & Quick Summary

Go refuses to compile code that other languages would accept with a warning:

code
./main.go:12:2: declared and not used: total ./main.go:4:2: "strings" imported and not used

Quick 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.

go
total := compute() // compile error if total is never read fmt.Println(total) // now it is used

This 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.

go
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") }
bash
go build ./... # ./main.go:5:2: "strings" imported and not used # ./main.go:9:2: declared and not used: total
DeclarationUnused is an errorWhy
local variable x := 1yesdead local code
local var x intyessame
function parameternopart of the signature
named return valuenomay be assigned later
package-level varnopossibly used by another file
struct fieldnoreflection and serialisation
type and methodnopart of the API
importyesunused dependency and compile cost
import with _noside effects only
import with alias .nomerged into file scope
Error textTriggerFix
declared and not used: xlocal never readuse it or delete it
declared and not used: errerror ignoredhandle or log it
imported and not used: "fmt"import removed from coderemove the import
x declared and not used after :=shadowing left outer unuseduse the outer variable or delete it
label defined and not usedgoto target removeddelete the label
no new variables on left side of :=all names already declareduse = for assignment

Key Comparison Table

SituationSafe fixUnsafe shortcut
Placeholder during refactordelete the declaration_ = x hides it forever
Interface satisfactionvar _ Reader = (*File)(nil)unused local with a comment
Import for side effectsimport _ "net/http/pprof"blank identifier on a normal import
Ignoring a return value_ = file.Close()leaving err unchecked
Debug printfmt.Println then remove both_ = fmt.Sprint
Range index unusedfor range itemsfor i := range plus _ = i
CategoryUnused allowedCommon mistake
package level varyesassuming it is an error
struct fieldyesadding _ = field needlessly
function parameteryesrenaming to _ and losing documentation
type parameteryesunused generic parameter compiles
methodyesdead method keeps building
importnoforgetting goimports
local variablenoleaving result after a refactor

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Leftovers from a refactor

go
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

go
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:

go
import _ "github.com/lib/pq" // registers the driver

3. err values that were never checked

go
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:

go
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

go
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 =:

go
var result string var err error if ok { result, err = doWork() } return err

5. Range variables

go
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
//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

  • _ = x to 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 vet confusion. vet reports different problems (printf verbs, lost cancels, loop closure capture before 1.22). The unused-variable rule is the compiler's, and go vet will not find it.
  • Test files. _test.go files follow the same rule; a helper assigned to a variable and never used fails go test compilation.
  • 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 slices and maps packages, and imports of them are only "unused" when the calls were removed.
  • Modules versus GOPATH. GO111MODULE=off builds 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 documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.