Fix

"imported and not used" Error in Go

This error occurs because Go's compiler enforces that every imported package must be explicitly referenced in the code to prevent unused dependencies.

This error occurs because Go's compiler enforces that every imported package must be explicitly referenced in the code to prevent unused dependencies. To fix it, either use a function, type, or constant from the package, or use a blank identifier (_) if you only need the package's side effects like initialization logic.

If you are importing a package to use its functionality, ensure you reference a specific symbol. For example, if you imported fmt but only used fmt.Println, the import is valid. However, if you imported os but never called os.Open or accessed os.Args, the compiler will flag it.

package main

import (
    "fmt"
    "os" // Error: imported and not used
)

func main() {
    fmt.Println("Hello")
    // os is imported but never used here
}

To resolve this, add a usage of the os package:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hello")
    _ = os.Args // Now 'os' is used
}

If you import a package solely for its init() function side effects (common with database drivers or logging setups), use the blank identifier _ to tell the compiler you intentionally want the import without using its exported symbols.

package main

import (
    _ "github.com/lib/pq" // Used for init() side effects only
    "fmt"
)

func main() {
    fmt.Println("Driver registered via init()")
}

You can also verify unused imports automatically using go vet, which is stricter than the compiler in some cases and helps catch these issues before building:

go vet ./...

If you are using a tool like gofmt or an IDE (VS Code, GoLand), they often provide a quick fix to remove the unused import entirely if you don't actually need the package. Simply delete the line from the import block if the package isn't required for logic or initialization.

Remember that Go does not allow unused imports even if they are commented out in the import block; the import must be syntactically present and used, or suppressed with _. This strictness keeps your binary size small and dependencies clear.