Fix

"imported and not used" in Go

This error occurs when you import a package but never reference any of its exported symbols (types, functions, or variables) in your code.

This error occurs when you import a package but never reference any of its exported symbols (types, functions, or variables) in your code. Go enforces strict rules to prevent unused imports, so you must either use the imported package or explicitly ignore it with a blank identifier (_) if you only need its side effects, such as initialization logic.

If you intended to use the package, simply reference one of its symbols. For example, if you imported fmt but forgot to call fmt.Println, the compiler will flag it.

package main

import "fmt"

func main() {
    // This usage satisfies the import requirement
    fmt.Println("Hello, world!")
}

If the import is required solely for its side effectsβ€”commonly seen with database drivers or crypto providers where the init() function registers the driver globallyβ€”you must use the blank identifier to tell the compiler you intentionally want the side effects without using the package name directly.

package main

import (
    "database/sql"
    _ "github.com/mattn/go-sqlite3" // Side effect: registers sqlite3 driver
)

func main() {
    // The driver is registered via the init() function in the sqlite3 package
    // We don't need to reference the package name directly here
    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        panic(err)
    }
    _ = db
}

In the second example, _ "github.com/mattn/go-sqlite3" imports the package and executes its init() function, which registers the "sqlite3" driver with the database/sql package. Without the underscore, the compiler would complain that the package is imported but not used, even though the registration is critical for the code to work.

If you are unsure why you imported a package, check if you are missing a function call or type reference. If you are building a plugin system or loading drivers, the blank identifier is the correct pattern. Never leave an unused import in your code, as it will prevent the build from succeeding.