Code Packages And Package Imports

Like many modern programming languages, Go code is also organized as code packages. To use the exported resources (functions, types, variables and named constants, etc) in a specified package, the package must first be imported, except the builtin standard code package. This article will explain code packages and package imports in Go.

Introduction Of Package Import

Let's view a small program which imports a standard code package. (Assume the source code of this program is stored in a file named simple-import-demo.go.)
package main

import "fmt"

func main() {
	fmt.Println("Go has", 25, "keywords.")
}
Some explanations: Run this program, we will get the following output:
$ go run simple-import-demo.go
Go has 25 keywords.

Please note, only exported resources in a package can be used in the source file which imports the package. Exported resources are the resources whose names are exported identifiers. For example, the first character of the identifier Println is an upper case letter (so the Println function is exported), which is why the Println function declared in the fmt standard package can be used in the above example program.

The built-in functions, print and println, have similar functionalities as the corresponding functions in the fmt standard package. Built-in functions can be used without importing any packages.

Note, the two built-in functions, print and println, are not recommended to be used in the production environment, for they are not guaranteed to stay in the future Go versions.

All standard packages are listed here. We can also run a local server to view Go documentation.

A package import is also called an import declaration formally in Go. An import declaration is only visible to the source file which contains the import declaration. It is not visible to other source files in the same package.

Let's view another example:
package main

import "fmt"
import "math/rand"

func main() {
	fmt.Printf("Next pseudo-random number is always %v.\n", rand.Uint32())
}

This example imports one more standard package, the math/rand package, which is a sub-package of the math standard package. This package provides some functions to produce pseudo-random numbers.

Some explanations: The above program will always output:
Next pseudo-random number is always 2596996162.

If we expect the above program to produce a different random number at each run, we should set a different seed by calling the rand.Seed function when the program just starts.

If multiple packages are imported into a source file, we can group them in one import declaration by enclosing them in a ().

Example:
package main

// Multiple packages can be imported together.
import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano()) // set the random seed.
	fmt.Printf("Next pseudo-random number is %v.\n", rand.Uint32())
}
Some explanations:

More About fmt.Printf Format Verbs

As the above has mentioned, if there is one format verb in the first argument of a fmt.Printf call, it will be replaced with the string representation of the second argument. In fact, there can be multiple format verbs in the first string argument. The second format verb will be replaced with the string representation of the third argument, and so on.

In Go 101, only the following listed format verbs will be used. An example:
package main

import "fmt"

func main() {
	a, b := 123, "Go"
	fmt.Printf("a == %v == 0x%x, b == %s\n", a, a, b)
	fmt.Printf("type of a: %T, type of b: %T\n", a, b)
	fmt.Printf("1%% 50%% 99%%\n")
}
Output:
a == 123 == 0x7b, b == Go
type of a: int, type of b: string
1% 50% 99%

For more Printf format verbs, please read the online fmt package documentation, or view the same documentation by running a local documentation server. We can also run go doc fmt to view the documentation of the fmt standard package, and run go doc fmt.Printf to view the documentation of the fmt.Printf function, in a terminal.

Package Folder, Package Import Path And Package Dependencies

A code package may be composed of several source files. These source files are located in the same folder. The source files in a folder (not including subfolders) must belong to the same package. So, a folder corresponds to a code package, and vice versa. The folder containing the source files of a code package is called the folder of the package.

Depending on different scenarios, a folder with name vendor might be viewed as a special folder. The following paragraphs will explain its specificity.

The lastest Go SDK (v1.11) introduces a module feature. Now, we can let a code package support the module feature or not. Go SDK 1.11 introduces a GO111MODULE environment variable. The default value of this environment variable is auto. Its two other possible values are on and off. If the value of the GO111MODULE environment variable is on, then all code packages support the module feature. If the value of the GO111MODULE environment variable is off, then all code packages don't support the module feature. If the value of the GO111MODULE environment variable is auto, then only the packages which satisfy both of the following two conditions support the module feature.
  1. the package folder must be outside all the src subfolders under the paths specified in the GOPATH environment variable.
  2. the package folder contains a go.mod file or is below a directory containing a go.mod file.

For a package doesn't support the module feature, generally, it is below a GOPATH/src directory. The import path of such a package is the relative path to the GOPATH/src directory or some vendor folder.

Assume all the packages in the following hierarchical directory structure don't support the module feature, then Note,
_ GOPATH
  |_ src
     |_ x
        |_ vendor
        |  |_ w
        |     |_ foo
        |        |_ foo.go    // package foo
        |_ y
        |  |_ vendor
        |  |  |_ w
        |  |     |_ foo
        |  |        |_ foo.go // package foo
        |  |_ y.go            // package y
        |_ z
        |  |_ z.go            // package z
        |_ x.go               // package x

For a package supports the module feature, its corresponding go.mod must specify the import path of the innermost folder containing the go.mod file. The format of specifying the import path is module ImportPath. Only the vendor folder which shares the same parent folder with the go.mod file is viewed as a special folder, but please note that the packages under the top-level vendor folder will be ignored if the build option -mod=vendor of go command tools is not provided in the building.

Assume all the packages in the following hierarchical directory structure support the module feature, then Note, when the x.go, y.go or z.go file imports a package with import path w/foo, the imported package is always the package with folder MyProject/vendor/w/foo.
_ MyProject
     |_ go.mod                // module example.com/mypkg
     |_ vendor
     |  |_ w
     |     |_ foo
     |        |_ foo.go       // package foo
     |_ x
        |_ y
        |  |_ vendor
        |  |  |_ w
        |  |     |_ foo
        |  |        |_ foo.go // package foo
        |  |_ y.go            // package y
        |_ z
        |  |_ z.go            // package z
        |_ x.go               // package x

Note, if a package folder contains a go.mod file, please don't put other go.mod files in its subfolders.

When one source file in a package import another package, we say the importing package depends on the imported package.

Go doesn't support circular dependency. If package a depends on package b and package b depends on package c, then source files in package c can't import package a and b, and source files in package b can't import package a.

Surely, source files in a package can't, and don't need to, import the package itself.

Later, we will call the packages named with main and containing main entry functions as program packages, and call other packages as library packages. Each Go program should contain one and only one program package.

The name of the folder of a package is not required to be the same as the package name. However, for a library package, it will make package users confused if the name of the package is different from the name of the folder of the package. The cause of the confusion is the default import path of a package is the name of the package but what is contained in the import path of the package is the folder name of the package. So please try to make the two names identical for each library package.

On the other hand, it is recommended to give each program package folder a meaningful name other than its package name, main.

The init Functions

There can be multiple functions named as init declared in a package, even in a source code file. The functions named as init must have not any input parameters and return results.

Note, at the top package-level block, the init identifier can only be used in function declarations. We can't declare package-level variable/constants/types which names are init.

At run time, each init function will be (sequentially) invoked once and only once (before invoking the main entry function). So the meaning of the init functions are much like the static initializer blocks in Java.

Here is a simple example which contains two init functions:
package main

import "fmt"

func init() {
	fmt.Println("hi,", bob)
}

func main() {
	fmt.Println("bye")
}

func init() {
	fmt.Println("hello,", smith)
}

func respectfulName(who string) string {
	return "Mr. " + who
}

var bob, smith = respectfulName("Bob"), respectfulName("Smith")
The output of this program:
hi, Mr. Bob
hello, Mr. Smith
bye

Resource Initialization Order

At run time, a package will be loaded after all its dependency packages. Each package will be loaded once and only once.

All init functions in all involved packages in a program will be invoked sequentially. An init function in an importing package will be invoked after all the init functions declared in the dependency packages of the importing package for sure. All init functions will be invoked before invoking the main entry function.

The invocation order of the init functions in the same source file is from top to bottom. Go specification recommends, but not requires, to invoke the init functions in different source files of the same package by the lexical file name order of their containing source files. So it is not a good idea to have dependency relations between two init functions in two different source files.

All package-level variables declared in a package are initialized before any init function declared in the same package is invoked.

A package-level variable is initialized after all of its depended variables. For example, in the following code snippet, the initializations the four package-level variables happen in the order y, z, x, and w.
func f() int {
	return z + y
}

func g() int {
	return y/2
}

var (
	w       = x
	x, y, z = f(), 123, g()
)

Full Package Import Forms

In fact, the full form of an import declaration is
import importname "path/to/package"

where importname is optional, its default value is the name (not the folder name) of the imported package. If the importname presents in an import declaration, then the prefix token used in qualified identifiers is importname.

The full import declaration form is not used widely. However, sometimes we must use it. For example, if a source file imports two packages with the same name, to avoid making compiler confused, we must use the full import form to set a custom importname for at least one package in the two.

Here is an example of using full import declaration forms.
package main

import (
	format "fmt"
	random "math/rand"
	"time"
)

func main() {
	random.Seed(time.Now().UnixNano()) // set the random seed
	format.Print("A pseudo-random number: ", random.Uint32(), "\n")
	
	// The following two lines fail to compile.
	/*
	rand.Seed(time.Now().UnixNano()) // set the random seed
	fmt.Print("A pseudo-random number: ", rand.Uint32(), "\n")
	*/
}
Some explanations:

The importname in the full form import declaration can be a dot (.). Such imports are called dot imports. To use the exported elements in the packages being dot imported, the prefix part in qualified identifiers must be omitted.

Example:
package main

import (
	. "fmt"
	. "time"
)

func main() {
	Println("Current time:", Now())
}

In the above example, Println instead of fmt.Println, and Now instead of time.Now must be used.

Generally, dot imports are not recommended to be used in formal projects.

The importname in the full form import declaration can be the blank identifier (_). Such imports are called anonymous imports (some articles elsewhere also call them blank imports). The importing source files can't use the exported resources in anonymously imported packages. The purpose of anonymous imports is to initialize the imported packages (each of init functions in the anonymously imported packages will be called once).

In the following example, all init functions declared in the net/http/pprof standard package will be called before the main entry function is called.
package main

import _ "net/http/pprof"

func main() {
	... // do somethings
}

Each Non-Anonymous Import Must Be Used Once

Except anonymous imports, other imports must be used at once. For example, the following example fails to compile.
package main

import (
	"net/http" // error: imported and not used
	. "time"   // error: imported and not used
)

import (
	format "fmt"  // okay: it is used once below
	_ "math/rand" // okay: anonymous packages are not required to be used
)

func main() {
	format.Println() // use the imported "fmt" package
}

The Go 101 project is hosted on both Github and Gitlab. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

Support Go 101 by playing Tapir's games. Cryptocurrency donations are also welcome:
Bitcoin: 1xucQbv5jujFPPwhyg395ri5yV71hx9g9
Ethereum: 0x5dc4aa2c2bbfaadae373dadcfca11b3358912212