What does an underscore in front of an import statement mean?

前端 未结 4 1132
梦如初夏
梦如初夏 2020-11-30 17:31

I saw this example from sqlite3 on GitHub :

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


        
4条回答
  •  清歌不尽
    2020-11-30 17:43

    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 {
        log.Println("theVeryFirstFunction")
        return 6
    }
    
    var (
        Num = theVeryFirstFunction()
    )
    
    func init() { log.Println("init", Num) }
    

提交回复
热议问题