Go Import Statement

As the Go language contains a vast array of functionality, it is split up into packages. The benefit of this is that a Go program need only include the packages that contains the functionality it requires to run and nothing more. Packages contain a collection of source code files that perform related tasks. Go includes many pre-built packages, which are collectively known as the standard library, however, packages can also be included from third-party sources. In order to utilise packages, either the pre-built ones, or those from an external source, the 'import' statement is used. Packages are imported below the 'package' statement, at the top of a program.

import "package_name"

An example of a package that is utilised frequently is 'fmt', which provides functionality to format input and output in a Go program.

import "fmt"

If multiple packages are required within a program, rather than using one 'import' statement for each, they can be grouped together.

import (
    "fmt"
    "strings"
)

Here, the 'strings' package, which is used for the manipulation of strings, is imported along with the 'fmt' package.

Packages can also be nested, one inside another.

import (
    "crypto/aes"
)

In this instance, the 'aes' package, which implements AES encryption, is nested inside the 'crypto' package.

Below are some examples of built-in packages, that make up part of the standard library.

  • crypto/aes - Provides a means for encryption using AES.
  • crypto/rand - Allows for the production of cryptographically secure random numbers.
  • errors - Implements functions to manipulate errors.
  • fmt - Allows for the formatting of input and output.
  • hash - Includes interfaces for hash functions.
  • math - Incorporates basic constants and mathematical functions.
  • net - Offers a portable interface for network I/O, including TCP/IP, UDP, domain name resolution and UNIX domain sockets.
  • os - Provides a platform independent interface to operating system functionality.
  • path - Includes utilities for manipulating slash-separated paths.
  • regexp - Implements regular expression searches.
  • strings - Provides functions to manipulate UTF-8 encoded strings.