Golang的进口声明前的下划线是什么意思? [英] What does an underscore in front of an import statement mean in Golang?

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

问题描述

我从这个例子> sqlite3 on GitHub

I saw this example from sqlite3 on GitHub :

import (
        "database/sql"
        "fmt"
        _ "github.com/mattn/go-sqlite3"
        "log"
        "os"
)

并且似乎无法找到导入语句前面的下划线的含义。

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 Specification

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

import _ "lib/math"



在sqlite3中



在<的情况下一个href =https://github.com/mattn/go-sqlite3/blob/master/sqlite3.go> go-sqlite3 ,下划线导入用于注册 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")

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

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