Import Packages in Go featured image

How to Import Packages in Go

Go (also known as Golang) is an open-source, statically typed programming language. It was originally developed by Google. Some notable features of Go include simplicity, high performance, readability, and efficiency.

Like any other prominent programming language, the standard library of Go offers a rich set of packages. However, we can also extend the functionalities by incorporating third-party packages. This guide will demonstrate importing packages and incorporating them into your Go projects.

Prerequisites

To follow this guide, you will need the following components prepared at your disposal:

Step 1 – Installing Go

We already discussed installing the core Go programming language on Ubuntu 20.04. However, there’s an easier alternative method: g  (a lightweight Go version manager).

The reason we are going to use g  is that neither of Go versions available from Ubuntu’s package repos or snap feature the latest Go version available (v1.18 at the time of writing this guide). It’s always recommended to use the latest version available of any programming language package.

The following command will run the g  installation script:

Import Packages in Go install go

Import Packages in Go installing go 2

To take the changes into effect, you have to restart the shell session. After restarting, verify the installation:

Import Packages in Go check go version

After installing Go, it’s also recommended to install gopls . It’s the official Go language server. It is compatible with many text editors like VS Code, Vim, Emacs, Sublime Text, Atom, and much more. Run the following command:

Our Go programming environment is now ready.

Step 2 – Creating a Sample Go Script

All the codes demonstrated in this guide will fit in a single Go script. Create a sample Go script:

After making changes to the script, we can run it using the following Go command:

Here, the Go compiler will run the code in interpreter mode.

Step 3 – Using Standard Library Packages

Go comes with a huge collection in its standard library. It consists of numerous packages, for example:

  • fmt: Implements formatted I/O with functions analogous to C ( printf  and scanf ).
  • http: This package provides functions for creating web services, sending and retrieving data over the http  protocol, etc.

To incorporate any package in a Go project, it has to be implemented using the import  statement. The statement is declared by the import  keyword along with the names of the packages. For example, to import math/rand , the import statement would look like this:

The following code implements various functions from the math/rand  package:

This code demonstrates a simple for loop that prints 10 random integers (0 to 24) on the screen. Here:

  • rand.Int() : This function call returns a random integer.
  • rand.Intn() : Acts similar to rand.Int()  but accepts a parameter that defines the range for random integers (from 0 to the number specified).

Next, run the code:

The output will look like this:

random number program

Note that the output will be exactly the same as the seed for the random number generator is a fixed value by default. This is the nature of a pseudorandom number generator. You can learn more about random seed here.

Step 4 – Importing Multiple Packages

Bigger and more complex projects need to incorporate multiple packages. How do you import them into your Go code? One valid option is to use individual import statements for each imported package. However, this approach is inefficient compared to the following import structure:

Here, a single import statement incorporates multiple packages at the same time. This reduces the amount of code necessary to write while improving readability.

The following code puts this feature into action:

Run the code:

The output will look something like this:

importing multiple packages

Step 5 – Installing Additional Go Libraries

The standard library of Go ships with numerous useful packages. Those are, by design, general-purpose. It enables developers to create their own packages on top of the standard library to meet their specific needs. Check out the official Go package database.

What if you need to implement a third-party Go package? Go ships with the go install  command ( go get  is deprecated). It can grab any third-party Go package from the internet.

For demonstration, we are going to install the cobra-cli  package. The following Go command will download and install the necessary files and integrate the package into the Go library system:

install cobra cli

The binary of cobra-cli  should be located at the following location:

list gopath files

The other package files should be located at the following location:

list package files

Starting from Go v1.11, Go modules define the version of the package you wish to import. This is explained in detail here: Go Modules GitHub.

Step 6 – Package Aliases

In various situations, you may find conflicting package names between the local and the imported packages. This is where aliasing can solve the collision. The aliasing structure looks something like this:

Let’s modify our simple Go program to incorporate fmt_alias  as an alias for the package fmt :

Notice that instead of using fmt.Printf() , we are using the package alias fmt_alias.Printf() .

However, Go is not so welcoming to aliases. When you are using aliases to avoid import name collision, it’s recommended to alias the most local or project-specific import. For example, if you want to have both a local package strings  and a system package strings , then you should alias the local package, not the system package.

The best practice is to avoid name collisions in the first place.

Step 7 – Imports Formatting

We learned to declare all the imports using a single import  statement. What if you had several imports? For example:

Imports formatting sorts the packages into a specific order, improving the consistency of the code. As it only sorts the order of the imports, it also prevents random commits. It also prevents unnecessary code churning and confusing code reviews.

Most modern editors will format the imports for you automatically. Alternatively, they will support goimports. It’s a common practice in the industry to use goimports  instead of manually sorting the imports. In addition, goimports  also reflects style changes in the code.

Here’s what the import  block may look like after applying goimports :

Notice any pattern?

  • All the standard libraries are grouped first.
  • The groups are separated by blank lines, improving the code readability.

Final Thoughts

Imports in Go is a powerful feature that allows calling functions not built into Go. While the standard library offers many general-purpose packages, Go also supports third-party packages. This guide demonstrates importing built-in and third-party Go packages.

In this guide, we ran our Go programs using the interpreter. However, you can compile the codes into standalone binaries for better performance. You can learn more about compiling Go programs here. If you want to learn how to deploy a Go web application with Nginx, check this tutorial. In addition, you can take a look at our guide that showcases how to write your own Go packages.

Are you a Go developer? CloudSigma offers Go API support for seamless integration with your projects.

Happy Computing!