A use case for importing with blank identifier in golang

前端 未结 3 1876
暖寄归人
暖寄归人 2020-12-15 06:32

The Go programming language specification states: \"To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name.\"

3条回答
  •  半阙折子戏
    2020-12-15 06:49

    This is because of the init function

    each source file can define its own niladic init function to set up whatever state is required. (Actually each file can have multiple init functions.)

    And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

    That is how the go-sqlite3 mentioned in "What does an underscore in front of an import statement mean in Go" works.

    func init() {
        sql.Register("sqlite3", &SQLiteDriver{})
    }
    

    You have another example in "Understanding Golang Packagese":

    In some contexts, we may need to import a package only for invoking it’s init method, where we don’t need to call forth other methods of the package.
    If we imported a package and are not using the package identifier in the program, Go compiler will show an error.
    In such a situation, we can use a blank identifier ( _ ) as the package alias name, so the compiler ignores the error of not using the package identifier, but will still invoke the init function.

提交回复
热议问题