patterngoCritical
What does an underscore in front of an import statement mean?
Viewed 0 times
underscorestatementdoesmeanfrontwhatimport
Problem
In this code from go-sqlite3:
what does the underscore in the
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)what does the underscore in the
import statement mean?Solution
It's for importing a package solely for its side-effects.
From the Go Specification:
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
In sqlite3
In the case of go-sqlite3, the underscore import is used for the side-effect of registering the
Once it's registered in this way, sqlite3 can be used with the standard library's
From the Go Specification:
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
import _ "lib/math"
In sqlite3
In the case of go-sqlite3, the underscore import is used for the side-effect of registering the
sqlite3 driver as a database driver in the init() function, without importing any other functions:sql.Register("sqlite3", &SQLiteDriver{})Once it's registered in this way, sqlite3 can be used with the standard library's
sql interface in your code like in the example:db, err := sql.Open("sqlite3", "./foo.db")Code Snippets
sql.Register("sqlite3", &SQLiteDriver{})db, err := sql.Open("sqlite3", "./foo.db")Context
Stack Overflow Q#21220077, score: 337
Revisions (0)
No revisions yet.