mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

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 the package declaration
  • The program will not compile if there are missing imports or unused ones
go
// 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:

go
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:

go
import name "import/path"

For example:

go
// Import the `math` package and use an explicit name `m` to refer to it
import 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:

go
package main
import (
"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:

go
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:

go
package main
import (
"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:

go
import (
"database/sql"
_ "github.com/lib/pq" // Import only for initialization
)