/errors/go/declared-and-not-used
Go: declared and not used: x
- tool
- Go
- exit code
- 1
- versions
- Go 1.20+ (message wording), Go 1.19 and earlier printed x declared but not used
- os
- any
declared and not used: x is a Go compile error, not a warning: a function declares the local variable x and never reads it. Go treats unused variables as errors on purpose, because they often point to a bug. Use the variable, delete it, or (temporarily) discard it with _ = x. Go 1.19 and earlier printed the same error as x declared but not used.
Example
package main
import "fmt"
func main() {
x := 42 // declared and not used: x
result, err := compute() // err is never read
fmt.Println(result)
}
func compute() (int, error) { return 1, nil }go build (or go vet, go run) stops with the file, line and column of each declaration, such as ./main.go:6:2: declared and not used: x. Both x and err are reported.
Fixes
// Use it
result, err := compute()
if err != nil {
return err
}
// Discard values you do not need
result, _ := compute()
// Keep a variable around while debugging
x := 42
_ = xShadowing: the subtle case
var err error
if cond {
data, err := load() // new err, shadows the outer one
use(data)
} // inner err is never read: declared and not used: err
return errDeclare data first and use =: var data []byte; data, err = load().
Unused imports
Imports follow the same rule: an import that is not used fails with "os" imported and not used. Remove it, or use import _ "pkg" when you only need the package's side effects (its init functions). goimports and gopls add and remove imports automatically.