问题描述
我看到了这个例子来自sqlite3
在 GitHub
上:
I saw this example from sqlite3
on GitHub
:
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
并且似乎无法找到 import 语句前面的下划线是什么意思.
and cannot seem to find what the underscore in front of an import statement means.
推荐答案
简答:
它用于导入一个包,只是为了它的副作用.
Short answer:
It's for importing a package solely for its side-effects.
来自 Go 规范:
要仅为其副作用(初始化)导入包,请使用空白标识符作为显式包名称:
导入_lib/数学"
在 sqlite3 中
对于 go-sqlite3,下划线import 用于在 init()
函数中将 sqlite3
驱动注册为数据库驱动的副作用,不导入任何其他函数:
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{})
一旦以这种方式注册,sqlite3 就可以在您的代码中与标准库的 sql
接口一起使用,如示例所示:
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")
这篇关于导入语句前面的下划线是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!