Skip to content
... imported and not used

... imported and not used

DodaTech 3 min read

The “… imported and not used” error means your Go source file imports a package that is never referenced in the code. Go treats this as a compile-time error to prevent bloated binaries and confusing dependencies.

What It Means

Go’s compiler is strict about code hygiene. Every imported package must be used somewhere in the file — calling a function, referencing a type, or accessing an exported constant. If the compiler detects an import that is never referenced, it stops with this error and refuses to build.

Why It Happens

  • You imported a package during development but never used it.
  • You removed code that referenced the import but forgot to remove the import statement.
  • You imported a package only for its side effects (e.g., database/sql driver registration) without using the blank identifier.
  • You refactored a function to no longer need a dependency.
  • You copied an import block from another file without using all the packages.

How to Fix It

1. Remove the unused import

The simplest fix is to delete the unused import line:

import (
    "fmt"    // unused — causes error
    "os"
)

// Fix: remove "fmt"
import (
    "os"
)

2. Use the blank identifier for side-effect imports

Some packages are imported solely for their init() functions, such as database drivers:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql" // blank identifier tells Go this is intentional
)

The _ alias satisfies the compiler that the import is intentional even though you never call a function from it.

3. Use goimports to fix automatically

The goimports tool automatically removes unused imports and adds missing ones:

# Install goimports
go install golang.org/x/tools/cmd/goimports@latest

# Fix all files in the current directory
goimports -l -w .

4. Use go mod tidy for module-level cleanup

For unused module dependencies in go.mod, run:

go mod tidy

This removes entries from go.mod for packages that are no longer imported anywhere in the module.

5. Check for conditional usage

If you use an import only inside an if block or behind build tags, the compiler still requires it at the file level. Consider splitting the file or using build-tag-specific files:

// File: main_linux.go
// +build linux

package main

import "syscall" // only used on Linux

FAQ

Why does Go treat unused imports as an error instead of a warning?
Go’s designers believe that unused imports slow compilation, increase binary size, and create misleading code. Making this a compile-time error enforces clean code and prevents dead dependencies from accumulating.
Can I keep an unused import temporarily while debugging?
No, the code will not compile. Comment out the import statement or use the blank identifier _ to silence the error temporarily. Remove it before committing.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro