Go - Imports
Imports are used when the source code depends on functionality of other packages:
- An
import
declaration declares a dependency relation between the importing and imported package - The
import
declarations must come after thepackage
declaration - The program will not compile if there are missing imports or unused ones
// Importing packages from the standard library.import "fmt"import "math"
Grouping Imports
It’s recommended to group imports using parentheses, this is called a factored import statement:
import ( "fmt" // The last element of the import path is the package name by convention // For example the files in this package `math/rand` begin with `package rand`. "math/rand")
Explicit Package Name
We can specify an explicit package name to refer to the imported package:
import name "import/path"
For example:
// Import the `math` package and use an explicit name `m` to refer to itimport m "math"// When the explicit package name is omitted it defaults// to the name specfied in the `package` clause of the imported package.import "fmt"
Example:
package mainimport ( "fmt" m "math")func main() { // Using `m.Pi` instead of `math.Pi`. fmt.Println(m.Pi)}
Explicit package names can be used to avoid conflicts when importing packages with the same name:
import ( crand "crypto/rand" "math/rand")
If an explicit period .
is used instead of an explicit name, all the exported identifiers declared in that package will be declared in the importing source file’s file block and must be accessed without a package name:
package mainimport ( "fmt" // Using a period `.` instead of a package name. . "time")func main() { // Using `Now()` instead of `time.Now()`. fmt.Println(Now())}
Import Package for Side Effects
To import a package only for its side-effects (initialization), the blank identifier _
is used as the explicit package name:
import ( "database/sql" _ "github.com/lib/pq" // Import only for initialization)