Go modules cheat sheet

Quick start

# Dependency Management
# add or upgrade dep
go get -d github.com/path/to/module
# use specific version
go get -d github.com/dep/two/v2@v2.1.0
# use specific branch
go get -d github.com/dep/commit@branch
# upgrade all modules used in subdirs
go get -d -u ./...

# remove dep
go get -d github.com/dep/legacy@none

# Useful commands
# organize and clean up go.mod and go.sum
go mod tidy
# download deps into module cache
go mod download
# initialize new module
go mod init github.com/path/to/module
# why is the module a dependency?
go mod why -m github.com/path/to/module
# build and install a binary
go install github.com/path/to/bin@latest

Anatomy of go.mod

module github.com/my/librarygo 1.16require ( github.com/dep/one v1.0.0 github.com/dep/two/v2 v2.3.0 github.com/dep/other v0.0.0-20180523231146-b3f5c0f6e5f1 github.com/dep/legacy v2.0.0+incompatible)exclude github.com/dep/legacy v1.9.2replace github.com/dep/one => github.com/fork/oneGo import path for where the module is hostedGo version used to develop the module(to use new language features)v2 and later have the major version in the module pathA “pseudo-version” that refers toa commit and not a tagged release“incompatible” means the packagehasn’t been migrated to Go modules yetReplace this module with this onePrevent a specificmodule versionfrom being used

Minimal Version Selection (MVS)

To build a program Go needs to know exactly which dependencies you need, and which version to use.

Go uses MVS as a predictable and simple way to decide which version to use.

It works like this:

  1. The module you’re running from is the “main module”
  2. Find all dependencies the main module needs (recursively, using the dependencies’ go.mod files)
  3. For each dependency, use the greatest version that any go.mod explicitly specified

Example

In this example, the main module depends on A 1.0 and B 2.1.

Since B 2.1 depends on A 1.1, this is the version of A that will be used.

Since A 1.1 is used, it also pulls in C 1.1.

The final dependency list is:

  • A 1.1
  • B 2.1
  • C 1.1

© 2021 André Eriksson — encore.dev
Contributions welcome at https://github.com/encoredev/cheatsheets (MIT License)