0
0
GoHow-ToBeginner · 3 min read

How to Use Blank Import in Go: Syntax and Examples

In Go, a blank import uses an underscore (_) as the package name to import a package solely for its side effects, like running its init() function, without directly referencing it in your code. This is done by writing import _ "package/path".
📐

Syntax

The blank import syntax uses an underscore (_) as the alias for the imported package. This tells Go to import the package only for its side effects, such as running the package's init() function, without using any exported names from it.

  • import _ "package/path": imports the package but does not bind it to a name.
  • This is useful when the package registers itself or performs setup automatically.
go
import _ "package/path"
💻

Example

This example shows how to use a blank import to register a database driver. The driver package runs its init() function automatically, enabling the main program to use it without directly referencing the package.

go
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/mattn/go-sqlite3" // blank import to register SQLite driver
)

func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	fmt.Println("SQLite driver registered and database opened successfully.")
}
Output
SQLite driver registered and database opened successfully.
⚠️

Common Pitfalls

Common mistakes when using blank imports include:

  • Importing a package with a blank import but expecting to call its functions directly, which causes compile errors.
  • Using blank imports unnecessarily, which can confuse readers about why the package is imported.
  • Forgetting that blank imports only run init() functions and do not provide access to package functions or types.

Always use blank imports only when you need the package's side effects, like registration or initialization.

go
package main

import (
	"fmt"
	_ "fmt" // Wrong: blank import of fmt, but no direct usage
)

func main() {
	fmt.Println("Hello") // Compile error: undefined: fmt
}

// Correct usage:
// import "fmt"
// func main() {
//     fmt.Println("Hello")
// }
📊

Quick Reference

Use blank imports when you want to:

  • Run a package's init() function without using its exported names.
  • Register plugins, drivers, or codecs that self-register on import.
  • Avoid unused import errors for packages used only for side effects.

Key Takeaways

Use blank imports with import _ "package/path" to run package init functions without direct usage.
Blank imports are useful for registering drivers or plugins that self-initialize.
Do not expect to call functions from a blank-imported package; it only runs side effects.
Avoid unnecessary blank imports to keep code clear and maintainable.