Using Blank Identifier in Go Imports for Initialization
The Go specification recommends using the blank identifier as an explicit package name to import a package solely for its side effects. However, the purpose of this construct may not be apparent.
One real-life use case is to initialize database drivers without using their exported functions. Consider the following example:
package main import ( _ "github.com/jackc/pgx/v4/reflect" "github.com/jackc/pgx/v4" ) func main() { conn, err := pgx.Connect(ctx, "user=jack password=secret database=world") if err != nil { log.Fatal(err) } _ = conn }
In this snippet, the _ "github.com/jackc/pgx/v4/reflect" import sets up a database connection by initializing the PostgreSQL driver with the init function. Since we don't need to use any of the exported functions of the reflect package, we use the blank identifier instead of a package alias.
Another example is setting up global state:
package main import ( _ "github.com/go-redis/redis/v9" "log" ) func init() { // Set up global Redis client client := redis.NewClient(redis.Options{ Addr: "localhost:6379", }) if err := client.Ping().Err(); err != nil { log.Fatalf("unable to connect to Redis: %v", err) } clientInfo, err := client.Info("Memory").Result() if err != nil { log.Fatalf("unable to get Redis info: %v", err) } log.Printf("Redis info: %s", clientInfo) } func main() { // Do stuff with the initialized global Redis client }
Here, the _ "github.com/go-redis/redis/v9" import invokes the init function to establish a global Redis connection. By using the blank identifier, we avoid using a package alias and allow the compiler to ignore it, while still benefiting from the initialization.
The above is the detailed content of When and Why Use Blank Identifiers in Go Imports?. For more information, please follow other related articles on the PHP Chinese website!