2014-01-19 17:25
浏览 283


I saw this example from sqlite3 on GitHub :

import (
        _ ""

and cannot seem to find what the underscore in front of an import statement means.

图片转代码服务由CSDN问答提供 功能建议

我看到了此示例摘自 GitHub 上的 sqlite3

“数据库/ sql” 
“ fmt” 
” log“ 
” os“ 


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • drouie2014 2014-01-20 01:52

    Short answer:

    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:

    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")
    打赏 评论
  • duanfan1965 2014-01-19 17:40

    It's either a work in progress, or imported for side effects. In this case, I believe it's for the side effects, as described in the doc.

    打赏 评论
  • doujiao7325 2016-09-09 07:46

    While other answers described it completely, for "Show me The Code" people, this basically means: create package-level variables and execute the init function of that package.

    And (if any) the hierarchy of package-level variables & init functions of packages that, this package has imported.

    The only side effect that a package can make, without being actually called, is by creating package-level variables (public or private) and inside it's init function.

    Note: There is a trick to run a function before even init function. We can use package level variables for this by initializing them using that function.

    func theVeryFirstFunction() int {
        return 6
    var (
        Num = theVeryFirstFunction()
    func init() { log.Println("init", Num) }
    打赏 评论

相关推荐 更多相似问题