Import syntax for package
When writing Go code, import is often used to import packages. The following reference is as follows:
import( "fmt" )
Then in the code, you can call it in the following way:
( "I love Beijing * Square" )
fmt is Go's standard library. It actually uses GOROOT to load the module. Of course, Go's import also supports the following two ways to load modules written by yourself:
Relative path
import "./model" // The current file in the same directory model Table of contents,But this method is not recommended import
Absolute path
import "shorturl/model" // load GOPATH/src/shorturl/model Module
Special usage of import of package
The above shows some commonly used import methods, but there are also some special imports, which are very puzzled by many novices. The following are three ways to use import packages.
Click Operation
Sometimes I see the following method to import the package:
import( . "fmt" )
The meaning of this point operation is that after importing this package, when you call the function of this package, you can omit the prefixed package name, which is what you called before:
( "I love Beijing * Square" )
Writing that can be omitted:
Println( "I love Beijing * Square" )
Alias Operation
Alias operation, as the name implies, can name the package as another name that is easy to remember:
import( f "fmt" )
When the alias operation calls the package function, the prefix becomes a renamed prefix, that is:
( "I love Beijing * Square" )
Underline operation
This operation is often an operator that many people are puzzled by. Please see the following import
import ( “database/sql” _ “/ziutek/mymysql/godrv” )
The sliding line "_" operation is actually just to introduce the package. When importing a package, all its init() functions will be executed, but sometimes it does not really need to use these packages, just wanting its init() function to be executed. At this time, you can use the "_" operation to refer to the package. Even if using the "_" operation to refer to the package, it is impossible to call the export function in the package through the package name, but it is just to simply call its init() function.
The above detailed explanation of the grammar of Golang import package is all the content I share with you. I hope you can give you a reference and I hope you can support me more.