Golang import import package syntax and some special usage details

  • 2020-10-07 18:44:20
  • OfStack

Import syntax for package

import is often used to import packages when writing Go code, as follows:


import(
  "fmt"
)

It can then be called in the code in the following way:


fmt.Println( " I love the home of scripts " )

fmt is the standard library of Go. It actually goes to GOROOT to load the module. Of course, import of Go also supports the following two ways to load the module written by itself:

Relative paths


import  "./model" //  Current file is the same as 1 The directory  model  Directories, but this approach is not recommended  import

An absolute path


import  "shorturl/model" //  loading  GOPATH/src/shorturl/model  The module 

Special use of package imports

There are 1 common ways to use import shown above, but there is also a special import that is confusing to many beginners. Here are 3 ways to use import packages.

Point of operation

Sometimes you'll see packages imported as follows:


import( 
  . "fmt" 
)

The point operation means that when you call the package's functions after the package is imported, you can omit the prefix package name, which you called earlier:


fmt.Println( " I love the home of scripts " )

Can be omitted as:


Println( " I love the home of scripts " )

The alias operation

The alias operation, as the name implies, can name a package to another name that is easy to remember:


import( 
  f "fmt" 
) 

The prefix becomes the renamed prefix when the alias operation calls the package function, that is:


f.Println( " I love the home of scripts " )

Underline operation

This is often a confusing 1 operator, see import below


import ( 
   " database/sql "  
  _  " github.com/ziutek/mymysql/godrv "  
) 

The slide "_" operation is really just introducing the package. When importing a package, all of its init() functions are executed, but sometimes you don't really need to use these packages, just want its init() functions to be executed. At this point, you can reference the package with the "_" operation. Even referring to a package with the "_" operation does not call the exported function in the package by the package name, but simply calls its init() function.

See the links below for more on the Golang import import package syntax and some special USES


Related articles: