What are go.mod and go.sum in Go?

Created Jan 17, 2024Last modified Jan 18, 2024
Go

Go Basics


go.mod and go.sum are two important files introduced with the inception of Go modules. They are used for managing dependencies and ensuring reproducibility in Go projects.

The go.mod file is the module definition file. It describes the module's name, its dependencies, and the Go version compatibility.

Example go.mod file:

module github.com/yourusername/yourproject

go 1.16

require (
    github.com/example/package v1.2.3
    github.com/another/package v0.4.1
)

It primarily does 3 things:

  1. Specifies the name of the module, often in the form of a path to a version control repository (e.g. module github.com/yourusername/yourproject).
  2. Specifies the minimum Go version required for the module.
  3. Lists the direct dependencies of the module, including their versions and any necessary replacements.

The go.sum file contains the expected cryptographic checksums of the content of specific module versions. It ensures that your project can reproduce the exact set of dependencies, preventing unauthorized changes or tampering.

Example go.sum file:

github.com/example/package v1.2.3 h1:abc123...
github.com/example/package v1.2.3/go.mod h1:def456...
github.com/another/package v0.4.1 h1:xyz789...
github.com/another/package v0.4.1/go.mod h1:uvw321...

It lists the specific versions of dependencies, each associated with a cryptographic hash. If any replacements are specified in go.mod, the checksums for the replacement modules are also included.

Managing Dependencies

Initialization

You can initialize Go modules in a project by running this:

go mod init <module-name>

Adding Dependencies

To add dependencies to your project:

go get <package>

This updates both go.mod and go.sum.

Updating Dependencies

To update dependencies based on version constraints specified in go.mod:

go get -u

Cleaning Up Dependencies

To remove unused dependencies and clean up go.mod and go.sum:

go mod tidy