import语句前面的下划线是什么意思? [英] What does an underscore in front of an import statement mean?

查看:123
本文介绍了import语句前面的下划线是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sqlite3上看到了此示例c1> :

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规范:

要仅出于副作用(初始化)导入软件包,请使用空白标识符作为显式软件包名称:

To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:

导入_"lib/math"

import _ "lib/math"

在sqlite3中

对于 go-sqlite3 ,下划线import用于将sqlite3驱动程序注册为init()函数中的数据库驱动程序的副作用,而无需导入任何其他功能:

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")

这篇关于import语句前面的下划线是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆