Go

Fix Go "Declared and Not Used" and "Imported and Not Used" Compile Errors

These two errors are not warnings and there is no flag that softens them: a Go program with a local variable nobody reads, or an import nobody names, does not build at all. This guide reproduces both messages exactly as the compiler prints them, states the rule each one enforces — including the boundary cases, where an assignment does not count as a use but an increment does — and works through the fixes in the order they should be tried, because the first error is usually a dropped value that was meant to be used, and only the last resort is telling the compiler the discard was deliberate.

Written November 18, 2026 · Tested with Go 1.26.4 · 27 min read

By the end of this guide
  • The first error: a variable nobody reads
  • The second error: an import nobody names
  • Both errors at once
  • The exact rule

What this guide is

Two of the first errors a Go programmer meets have nothing to do with what a program does. Nothing in them is a type mismatch, a missing symbol, or a logic fault. One says a variable was declared and never used; the other says a package was imported and never used. Both are compile errors — not warnings, and not linter findings that a configuration file can relax — so a program carrying either one produces no executable at all until the code changes. The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir unused
$ cd unused
$ go mod init example.com/unused
go: creating new go.mod: module example.com/unused

Each program that follows replaces the contents of that main.go. The module line matters to the error output: when a build fails, the compiler prints the package it was building as a header line above the errors, and that header is the module path — # example.com/unused here. The file, line, and column in each message point at the declaration itself, not at the place where a use was expected: it names where the unused thing was born, and the rest of the function — or the rest of the file, for an import — is where the missing use was supposed to be.

The two rules look like twins and are usually taught together, but they differ in scope in ways that decide the fix. The variable rule reaches only variables declared inside a function body. The import rule reaches every import in every file, and its one sanctioned escape — the blank import — means something different from the blank assignment that escapes the variable rule. Keeping the two apart is most of the guide.

The first error: a variable nobody reads

The smallest program that earns the variable error declares one local variable and then does nothing with it:

Go
// main.go
package main

func main() {
    x := 1
}
Terminal
$ go build
# example.com/unused
./main.go:4:2: declared and not used: x

Read the message in its three parts. The position, ./main.go:4:2, is the declaration: line 4 is the x := 1 line, and column 2 is where x sits after the tab. The wording, declared and not used, states the whole rule — a declaration happened, and no use followed it. The trailing : x names the variable, which is what makes the message actionable in a long function: when several variables are declared and only one is dropped, the compiler names the dropped one rather than the function. There is no second line of explanation, because from the compiler's side there is nothing more to say: the program is rejected not for doing something wrong with x, but for never doing anything with x at all.

Note what the program does not contain. There is no misspelling, no shadowing, and no second variable competing for attention — the patterns that produce this error in real code, where a result is computed into one name and printed from another, or a refactored function keeps a declaration whose only use was deleted. The minimal program isolates the rule: a single declaration with zero reads is already the whole offense, and any larger program that earns this message contains this same shape somewhere inside it.

The second error: an import nobody names

The import error is the same shape one level up. A file imports a package and then never refers to any identifier from that package:

Go
// main.go
package main

import "fmt"

func main() {
}
Terminal
$ go build
# example.com/unused
./main.go:3:8: "fmt" imported and not used

The position is again the declaration: line 3 is the import line, and column 8 is where the quoted path "fmt" begins. The path is printed in quotes, exactly as it appears in the import, which matters when a file imports several packages — the message names the unused path, not a position in a list. An import counts as used only when the file actually refers to an exported identifier of the package, as in fmt.Println. Merely having the import present does not count. The scope here is the file, not the package: imports are declared per file, so a package spread over three files may use fmt heavily in two of them, and the third file still fails if it imports fmt and names nothing from it.

Both errors at once

The two checks are independent, and one build reports every offense it finds in the file rather than stopping at the first. A file carrying both faults produces both messages in a single run, in file order:

Go
// main.go
package main

import "fmt"

func main() {
    x := 1
}
Terminal
$ go build
# example.com/unused
./main.go:3:8: "fmt" imported and not used
./main.go:6:2: declared and not used: x

This is worth knowing before fixing either error in a large file. Fixing the first message and rebuilding is not a loop that reveals one new error at a time; the full list is already in the first output. The two fixes can also be chosen independently — the import is fixed at the top of the file, the variable inside the function — unless the intended fix for the variable was to print it, which would have used the import as well. That interaction is common enough that it is worth a look before deleting an import: a dropped fmt.Println call near the end of a half-finished function is frequently the single cause behind both messages.

The exact rule

Stated precisely, the variable rule is this: a variable declared inside a function body must be used — read — at least once within its scope, or the program does not compile. The declaration form makes no difference. A short declaration with := is the usual source, but a var declaration inside a function is held to the same standard, with the position pointing into the declaration:

Go
// main.go
package main

func main() {
    var x int
}
Terminal
$ go build
# example.com/unused
./main.go:4:6: declared and not used: x

The import rule, stated precisely, is this: a file may not import a package without referring to any of its exported identifiers. The one exception is written into the import itself — importing with the blank identifier as the package name, import _ "fmt", which declares that the package is imported for its side effects and is covered in its own section below.

The two rules also differ in where their authority sits, and the difference explains their slightly different shapes. For imports, the language specification states the rule directly: it is illegal to directly import a package without referring to any of its exported identifiers. For variables, the specification phrases it as an implementation restriction — a compiler may make it illegal to declare a variable inside a function body if the variable is never used — and the standard Go compiler exercises that permission, always. So in practice both are unconditional errors from the toolchain every Go programmer uses, but only the import rule is a mandate of the language definition itself.

What neither rule has is an escape hatch in the toolchain. There is no compiler flag that turns these errors into warnings, and no warning setting to turn up or down: the Go compiler reports errors that prevent compilation, not warnings, and an option that changed whether a program compiles would change the meaning of the language from build to build. The Go FAQ addresses the request for such an option directly — it has not been added, for exactly that reason — and gives the rationale for the checks themselves: the presence of an unused variable may indicate a bug, while unused imports slow down compilation, an effect that becomes substantial as a program accumulates code and programmers over time. Go therefore refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity.

Assignment is not a use

The most misleading near-miss is a variable that is written to repeatedly and read never. Writing feels like using — the variable appears on line after line, the function looks busy — but the rule counts reads, and an assignment target is not a read:

Go
// main.go
package main

func main() {
    x := 1
    x = 2
}
Terminal
$ go build
# example.com/unused
./main.go:4:2: declared and not used: x

The error is identical to the one-line case, and the position still points at the declaration on line 4, not at either assignment: the value 2 is stored into x, the function ends, and nothing ever observes either value. In real code this shape is what remains when the reading code is removed from a longer function — a print deleted, a condition simplified — leaving assignments that compute a result nobody consumes. The assignments are the clue: the variable was being prepared for something, and the something is what went missing. The same principle decides subtler cases. A variable that appears only on the left side of every statement it touches is unused, no matter how many statements that is. A variable that appears on a right side even once — inside any expression that is actually evaluated — has been read. The next section catalogs the reading forms, including two that surprise people because they look like pure writes.

What counts as a use

A use is any read of the variable's value. The ordinary forms are passing the value somewhere, printing it, comparing it, and returning it, and one small program exercises all four:

Go
// main.go
package main

import "fmt"

func double(n int) int {
    return n * 2
}

func five() int {
    x := 5
    return x
}

func main() {
    a := 1
    fmt.Println(a)
    b := 2
    fmt.Println(double(b))
    c := 3
    if c > 2 {
        fmt.Println("big")
    }
    fmt.Println(five())
}
Terminal
$ go run main.go
1
4
big
5

Each variable is read exactly once, which is all the rule asks. a is read as an argument to fmt.Println. b is read as an argument to double. c is read by the comparison c > 2 — a read that produces no output of its own, but a read all the same, so a variable that exists only to be tested against a condition is used. x inside five is read by the return statement. A variable does not need to escape the function or be printed; it needs one evaluation that observes its value.

Two statement forms that look like writes also count, because each of them reads the current value in order to produce the next one. The increment statement is the first:

Go
// main.go
package main

func main() {
    x := 1
    x++
}
Command
$ go build

The build succeeds with no output: x++ reads x, adds one, and stores the result, so the variable has been used even though the new value is itself never read and the program prints nothing. Compound assignment is the second form, for the same reason — an assignment operation such as x += 2 is equivalent to x = x + 2 with x evaluated once, and the right-hand occurrence is a read:

Go
// main.go
package main

func main() {
    x := 1
    x += 2
}
Command
$ go build

This pair of results draws the line exactly. Plain assignment, x = 2, never looks at the old value, and does not count. Increment and compound assignment cannot do their work without the old value, and do count. The distinction matters as a diagnostic: when a variable with several assignments still earns the error, check whether any of those statements actually reads it, because the ones built on = alone never do.

What the rule does not reach

The variable rule has a hard boundary at the function body, and a second boundary around kinds of declaration that are not local variables at all. Everything on the far side of those boundaries may sit unused indefinitely. One program collects the exemptions:

Go
// main.go
package main

import "fmt"

var packageLevel = 10

const packageConst = 42

type point struct {
    x int
    y int
}

func unusedFunc() int {
    return 1
}

func helper(unusedParam int) int {
    return 7
}

func named() (result int) {
    return
}

func main() {
    const localConst = 99
    p := point{x: 1}
    fmt.Println(p.x, helper(0), named())
}
Terminal
$ go run main.go
1 7 0

The program compiles and runs, and an inventory of what it never uses shows how wide the exemptions are. packageLevel is a package-level variable that nothing reads; the rule governs variables declared inside a function body, and this one is declared outside any function. packageConst and localConst are constants, at package level and inside main respectively; constants are not variables, and neither is required to be referenced. The struct type point has a field y that is never read and never even set; struct fields are not local variables. unusedFunc is a package-level function that nothing calls; functions are declarations a package offers, not values a function body must consume. Inside helper, the parameter unusedParam is never mentioned in the body, and parameters are exempt — a signature often must accept a value the current implementation does not need, to satisfy an interface or a callback shape. Inside named, the named result result is never assigned explicitly; the bare return returns its zero value, which is why the program prints 0 for it, and named results are exempt for the same reason parameters are — they belong to the signature, not to the body's local declarations.

The pattern is consistent: the rule polices declarations a function body makes for its own private use, where an unused name can only be clutter or a bug. Declarations that form part of a larger surface — a package's variables and functions, a type's fields, a function's signature — may be used from elsewhere, or later, and the compiler leaves them alone. When the error does fire, its scope is also its information: the unused thing is local and recent, and the fix is a local decision.

The blank identifier: the deliberate discard

Go's answer to a value that genuinely must be received but not kept is the blank identifier, _. The blank identifier is an anonymous placeholder: it may be used like any other identifier in a declaration, but it introduces no binding and is not itself declared, so there is nothing for the unused rule to attach to. Assigned to a variable, it reads the value and discards it, which converts an unused variable into a used one:

Go
// main.go
package main

func main() {
    x := 1
    _ = x
}
Command
$ go build

The build succeeds. _ = x is an ordinary assignment statement whose left side is the blank identifier — the specification allows the blank identifier as an assignment operand on the left side of an = assignment, and any typed value may be assigned to it — so x is evaluated, read, and thrown away on purpose. That is the entire mechanism, and its honesty is its virtue and its danger: the line states, in code, that the discard is deliberate. Used where the discard is real, it is the correct fix. Used to silence an error whose cause was never examined, it writes a false statement into the program.

The limits of the mechanism matter as much as the mechanism. A blank assignment operates on values, and an unused import is not a value problem, so the same line does nothing for the import error:

Go
// main.go
package main

import "fmt"

func main() {
    x := 1
    _ = x
}
Terminal
$ go build
# example.com/unused
./main.go:3:8: "fmt" imported and not used

The variable error is gone and the import error remains, untouched, because nothing in the function body can use an import — only a reference to one of the package's exported identifiers can. During development, that reference can itself be made with the blank identifier, as a package-level declaration that names a symbol purely to mark the import as used for now:

Go
// main.go
package main

import "fmt"

var _ = fmt.Printf

func main() {
}
Command
$ go build

This is a recognized scaffolding move rather than a finish: Effective Go's convention is that such blank declarations sit immediately after the imports and carry a comment marking them for deletion, because they exist to let a half-written file compile while work continues. The FAQ's version of the same trick carries the same warning in its comment — delete before committing. A var _ = fmt.Printf that survives into finished code is worse than the error it silenced, because it disguises a leftover as a decision. Distinct from both tricks is the blank import, where the blank identifier replaces the package name in the import itself:

Go
// main.go
package main

import _ "fmt"

func main() {
}
Command
$ go build

This compiles, and it is the form the specification prescribes for importing a package solely for its side effects — its initialization. A blank-imported package has no name in the file, so none of its identifiers can be referenced at all; the import is satisfied because the blank name states explicitly that side effects are the whole point. That is also why the blank import of fmt above, while legal, is pointless: fmt has no initialization side effects worth importing for. The form earns its place with packages whose init functions do real registration work — Effective Go's example is net/http/pprof, whose initialization registers HTTP handlers, imported as import _ "net/http/pprof" by programs that never call it directly. Used to quiet an ordinary unused-import error, the blank import gets the semantics backwards: it claims the file wants the package's invisible behavior, which is false for fmt, strings, and the rest of the everyday library.

Multi-value declarations: one name too many

Short declarations often bind several values at once, and the rule applies per name, not per statement. When a function returns two values and only the first is used, the error names the second:

Go
// main.go
package main

import "fmt"

func pair() (int, int) {
    return 1, 2
}

func main() {
    a, b := pair()
    fmt.Println(a)
}
Terminal
$ go build
# example.com/unused
./main.go:10:5: declared and not used: b

The position, line 10 column 5, is the position of b inside the declaration — the compiler locates the unused name within the list, so in a declaration binding three or four values the message still points at the one name that is never read. Because the offense is per name, the fix is per name as well: replace the unwanted name with the blank identifier at the declaration itself, rather than declaring it and discarding it afterward:

Go
// main.go
package main

import "fmt"

func pair() (int, int) {
    return 1, 2
}

func main() {
    a, _ := pair()
    fmt.Println(a)
}
Terminal
$ go run main.go
1

Writing a, _ := pair() is better than a, b := pair() followed by _ = b: the intent is stated where the value arrives, no reader has to track a name that exists only to be discarded, and no real variable is created at all — the blank identifier introduces no binding. The same per-name logic governs range clauses, where the unwanted name is usually the index:

Go
// main.go
package main

import "fmt"

func main() {
    s := []int{10, 20}
    for i, v := range s {
        fmt.Println(v)
    }
}
Terminal
$ go build
# example.com/unused
./main.go:7:6: declared and not used: i
Go
// main.go
package main

import "fmt"

func main() {
    s := []int{10, 20}
    for _, v := range s {
        fmt.Println(v)
    }
}
Terminal
$ go run main.go
10
20

A loop that needs only the values discards the index in the clause itself. The mirror case — needing the index and not the value — discards the value the same way, and a loop that needs neither writes the range clause with no variables at all, for range s, rather than discarding two names.

Born in an if or for header

A short declaration does not have to stand on its own line to be a local declaration. The specification allows short variable declarations in the initializers of if, for, and switch statements, where they declare local temporary variables — and a temporary that is never read earns the same error as any other local variable:

Go
// main.go
package main

import "fmt"

func main() {
    if x := 1; true {
        fmt.Println("yes")
    }
}
Terminal
$ go build
# example.com/unused
./main.go:6:5: declared and not used: x

Here x is declared in the if initializer and then ignored by both the condition and the body — the condition is the constant true, and the body prints a literal. The declaration was presumably meant to feed one of them. The fix, when the value is wanted, is to let it do its job in the condition or the body:

Go
// main.go
package main

import "fmt"

func main() {
    if x := 1; x > 0 {
        fmt.Println(x)
    }
}
Terminal
$ go run main.go
1

The for form behaves identically. A variable declared in a for clause that the condition, the post statement, and the body all ignore — for x := 0; true; { break } — fails with ./main.go:4:6: declared and not used: x, pointing into the clause. In practice the for case is rarer, because a loop variable is usually load-bearing in the condition or the post statement by construction; when it is not, the loop was probably meant to be a plain for with no clause at all, and deleting the declaration is the fix. Header declarations are also where the error most often signals a logic slip rather than clutter: the scope of an if-header variable is exactly the statement, so an unused one means the test the programmer set up is not the test the statement is running.

The fixes, ranked

Three fixes cover every case in this guide, and the order matters, because they make different claims about the code. The first claims the value was always meant to be used. The second claims the declaration was never needed. The third claims the value is received on purpose and thrown away on purpose.

Use it. The first fix is to find the use the value was meant to have and restore it. Most unused-variable errors in working code are not clutter; they are the visible half of a dropped operation — a result computed and never printed, a total accumulated and never compared, a value produced and never checked. The compiler cannot say what the use was, but the assignments around the declaration usually can, and the variable's name almost always does. For the opening example, using the variable is the one-line change the error was asking for all along:

Go
// main.go
package main

import "fmt"

func main() {
    x := 1
    fmt.Println(x)
}
Terminal
$ go run main.go
1

Remove it. When no use was ever intended — the declaration is a leftover from an earlier draft of the function, the import was added speculatively and the code took another path — the correct fix is deletion. Delete the variable's declaration and every assignment that fed only it; delete the import line. Removal is the fix the FAQ's rationale points at for imports in particular: an unused import is not neutral, it slows compilation and misleads the next reader about what the file depends on.

Blank-assign only when the discard is the intent. The third fix is the blank identifier, and its legitimate home is narrow: a value that a statement is forced to produce, that the program genuinely does not need, where the receiving code must say so explicitly. The canonical shape is one side of a two-value operation. A map index expression, for instance, yields an optional second value reporting whether the key was present, and code that wants the presence flag but not the value — or the value but not the flag — discards the other half in the declaration:

Go
// main.go
package main

import "fmt"

func main() {
    m := map[string]int{"one": 1}
    v, _ := m["one"]
    fmt.Println(v)
    _, ok := m["two"]
    fmt.Println(ok)
}
Terminal
$ go run main.go
1
false

Both discards here are real decisions: v, _ states that the presence flag for a key the code is certain about is not needed, and _, ok states that the value stored under "two" is irrelevant next to the fact of its absence. The same form serves multi-value function calls, as the pair example showed. What the blank form should not be used for is the first two fixes' territory: not for a value whose use was dropped (that is a bug being papered over), and not for a declaration that nothing needs (that is clutter being preserved). The development scaffolding forms — _ = x to keep a half-written function compiling, var _ = fmt.Printf to hold an import in place — are legitimate precisely because they are temporary and visibly marked as such; once the code is meant to be finished, each one is a promise to go back and apply fix one or fix two.

For imports specifically, one more option belongs in the ranking between removal and the blank import: let a tool keep the import block honest. The FAQ notes that most Go programmers use goimports, which rewrites a source file to have the correct imports — adding ones the code references and removing ones it does not — eliminating the unused-imports issue in practice, with the same functionality built into the gopls language server. The rule is unchanged; an editor that reconciles imports on save simply means the commonest cause — an import orphaned by an edit — is cleaned up at the moment it is created.

Which fix for which cause

What the code shows Cause Fix
A local variable is computed and assigned but never read, and its name or the surrounding code shows a use it was meant to feed The use was dropped — a print, check, or return was removed or never written Use it: restore the missing read; for an import error in the same file, check whether the restored use also consumes the import
A local variable's only appearances after its declaration are plain = assignments Assignment is not a use — the value is prepared and never consumed Find the missing read, or remove the declaration and its assignments if no read was ever intended
A local variable or import is a leftover from an earlier draft, with no intended use anywhere Dead declaration Remove it — the declaration line for a variable, the import line for a package
One name in a multi-value declaration (a, b := ..., a range clause, a two-value map index) is never read while the other is Only that value is unwanted; the operation itself is needed Replace that one name with _ at the declaration: a, _ := pair(), for _, v := range s, _, ok := m[k]
A variable declared in an if or for header is never read by the condition, post statement, or body The header declaration is not feeding the statement it belongs to Use it in the condition or body if the test needs it; otherwise delete the declaration — a bare for or plain condition
A half-written file must compile while work continues, and the variable or import will be used shortly Development in progress, not finished code _ = x for the variable, or var _ = pkg.Symbol placed right after the imports and commented for deletion — scaffolding only, removed before the code is finished
A package is imported only so its init functions run, and the file never names it Side-effect import Blank import, import _ "pkg" — the sanctioned form, for packages imported for initialization such as net/http/pprof; never as a way to silence an ordinary unused import

Checklist

  • Before changing anything, read the position in the message: it points at the declaration — the variable's line, or the import line with the path in quotes — and the trailing name says exactly which declaration is unused.
  • Before deleting an import, check the whole build output: one run reports every unused variable and import in the file, and a dropped use inside the function may be the cause of both messages.
  • Before calling a variable used, find a read: a print, a pass, a comparison, a return, an increment, or a compound assignment. Plain = assignments, however many, do not count.
  • Before blank-assigning a variable, decide which claim is true: the use was dropped (restore it), the declaration is dead (remove it), or the discard is deliberate (only then use _).
  • Before blank-importing a package, confirm the package is imported for its initialization side effects. If the file will name the package later, the fix is to write the reference or remove the import — not to rename it to _.
  • Before treating an exemption as a loophole, check the boundary: parameters, named results, package-level declarations, struct fields, and constants are outside the rule by design, and local variables are inside it — moving a declaration across that line to dodge the error hides the problem it reported.

Sources

  • The Go Programming Language Specification — for the blank identifier (an anonymous placeholder that introduces no binding and is not declared, usable in declarations and on the left side of assignments, where any typed value may be assigned to it), for short variable declarations including their use in the initializers of if, for, and switch statements, for the variable implementation restriction (a compiler may make it illegal to declare a variable inside a function body if the variable is never used), for compound assignment (x op= y is equivalent to x = x op (y)), and for imports (it is illegal to directly import a package without referring to any of its exported identifiers, and a package is imported solely for its side effects by using the blank identifier as its explicit package name).
  • Go, Frequently Asked Questions (FAQ) — for the section "Can I stop these complaints about my unused variable/import?": an unused variable may indicate a bug while unused imports slow down compilation, Go refuses to compile programs with unused variables or imports and trades short-term convenience for long-term build speed and program clarity, no compiler option turns the checks off or reduces them to warnings because the Go compiler does not report warnings, the blank identifier is the development-time workaround, and goimports — also built into gopls — eliminates the unused-imports issue in practice.
  • Effective Go — for the blank identifier sections: it is an error to import a package or declare a variable without using it, blank declarations that silence import errors belong immediately after the imports, commented as a reminder to clean them up, assigning an unused variable to the blank identifier silences the variable error, and the import-for-side-effect form renames a package such as net/http/pprof to the blank identifier when only its initialization is wanted.

Keep Exploring