Overview
go mod is the command-level face of Go modules: a handful of subcommands that keep
go.mod (requirements) and go.sum (cryptographic checksums) in sync with what the code
actually imports. The deeper machinery — minimal version selection, the module proxy, the
checksum database — is covered in Go modules; this
note is the muscle memory.
Key points
go mod init example.com/mod: createsgo.modwith the module path — the import prefix for every package in the module.go mod tidy: the one you run constantly — adds missing requirements, drops unused ones, updatesgo.sum. Run it before every commit that touches imports; CI checkinggit diff --exit-code go.mod go.sumafter tidy is a common gate.go mod download: pre-fills the module cache (GOPATH/pkg/mod) — Docker layer caching's best friend (COPY go.mod go.sum+ download before copying source).go mod why -m <module>: shows the import chain explaining why a dependency exists;go mod graphdumps the full requirement graph for scripting.go mod vendor: materializes dependencies intovendor/for hermetic builds (-mod=vendor); mostly for locked-down CI or corporate environments — the module cache plus checksums usually suffice.go mod edit: scripted edits (-replace,-require,-go) — the mechanical tool; humans mostly editgo.moddirectly.go.modalso carries the toolchain: thegoline sets the minimum language version and the optionaltoolchain go1.x.yline names the toolchain to switch to when the local one is older. Both are floors, not pins — see The Go toolchain. Note that this makesgo.moda file the project owns and a provisioning file at once, so tooling that maintains it must merge the one directive in place rather than render the file.go.sumis not a lock file:go.modalready pins versions (MVS is deterministic);go.sumholds hashes so a tampered or republished module fails the build. Commit both.- Adding a dependency is implicit:
go get example.com/pkg@v1.2.3(or just importing it and running tidy);go get -u ./...upgrades.
Examples
go mod init github.com/rgoussu/widget
go get github.com/jackc/pgx/v5@latest
go mod tidy
go mod why -m golang.org/x/crypto
Related
- The Go toolchain — parent catalog.
- Go modules — MVS, proxy protocol, and sumdb behind these commands.
- go work — the workspace answer to cross-module local development.
- Build ecosystem (Java) — the Maven/Gradle world this replaces with one built-in subcommand.
- Version managers — why Go's built-in mechanism means the ecosystem needs no manager of its own.