Introduction to Go Modules

Table of Contents

  1. Preface
  2. Why Go Modules
  3. Philosophy
  4. Example

Preface

All the content for this post was gathered by reading the 7 part blog series by Russ Cox and other notes. There is also an introductory post on the Go blog. I would encourange you to read them as well.

Why Go Modules

Before jumping into the workings of Go modules, we should first understand why we need it in the first place. The current state of Go development has some drawbacks:

Philosophy

In order to understand Go modules, you have to understand a few key concepts.

Import Compatibility Rule

If an old package and a new package have the same import path, the new package must be backwards-compatible with the old package.

Minimal Version Selection

Defaults to using the oldest allowed version of every package involved in the build. These exclusions and replacements do not apply when the module is being built as a dependency of some other module. This gives users full control over how their own programs build, but not over how other people’s programs build.

Builds should be Reproducible / Verifiable / Verified

Reproducible is one that, when repeated, produces the same result. Verifiable is one that records enough information to be precise about exactly how to repeat it. Verified is one that checks that it is using the expected source code.

Example

Let’s explain with an example. We will first use go modules to create two versions of a library and push that module to github. Then we will create an executable, that uses this newly created library.

Module Creation

The library we create will print out messages in different colors. All code for this is available on github. Here are the steps to create this library:

We have now packaged our library gomodexample as a module and it can be used by anybody.

Module Use

Let’s try using the library we just created. Following similar steps as above:

Hopefully this tutorial has helped you understand Go modules better. Starting in Go 1.13 (August 2019) module mode will be enabled by default. The new features seem very promising and I for one am eager to start using Go modules more often.