The Analogy: The Bill of Materials
A building contract has two documents that look similar and do completely different jobs. The bill of materials lists what the job needs and the minimum acceptable grade of each item: structural steel of at least grade S275, cement of at least class 42.5. The certificates of authenticity are what arrive with each delivery, one per batch, so nobody can quietly substitute a cheaper grade halfway through.
go.mod is the bill of materials. It declares your module's own name -- the prefix every import path in it starts with -- the language version you are writing against, and one require line per direct dependency giving the minimum version you need. go.sum is the certificate file: a cryptographic hash for every module version in the graph, checked on every download. Neither is a lockfile in the npm sense, and understanding why is the whole lesson.
Here is the part that surprises people coming from other ecosystems. When two subcontractors ask for different minimum grades of the same steel, the site does not order the newest product in the catalogue -- it orders the highest minimum anybody asked for. That is Minimal Version Selection, and it is why Go needs no dependency solver, no lockfile to pin versions, and no resolution step that can produce a different answer tomorrow. Your build is a pure function of the go.mod files in the graph.
Where the analogy breaks down: the go line is not paperwork. It gates language features -- per-iteration loop variables only exist for modules declaring go 1.22 or later -- and since Go 1.21 the companion toolchain line will make the go command download and run a different toolchain than the one you invoked. And major version 2 and beyond is not a number in a field; it is a change to the module path itself, which is what allows one program to use two incompatible majors of the same library at once.
Syntax or Core Structure
go mod init example.com/shop
go get github.com/google/uuid@v1.6.0
go mod tidy
go build ./...
Output: go.mod now contains exactly this, and nothing was resolved twice:
module example.com/shop
go 1.22
require github.com/google/uuid v1.6.0
And go.sum gained two lines per module -- one for the code, one for that module's own go.mod:
github.com/google/uuid v1.6.0 h1:<base64 hash of the module zip>
github.com/google/uuid v1.6.0/go.mod h1:<base64 hash of its go.mod>
A fuller go.mod, with every directive that exists:
module example.com/shop/v2 // the import prefix; /v2 is part of the name
go 1.22 // language version: gates features
toolchain go1.22.5 // which toolchain to fetch and run
require (
github.com/google/uuid v1.6.0
golang.org/x/text v0.14.0 // indirect
)
require example.com/internal-tool v0.3.1
replace example.com/internal-tool => ../internal-tool // main module only
exclude github.com/bad/lib v1.2.3 // main module only
retract v2.0.1 // for authors: withdraw a release you published
The // indirect marker means "nothing in this module imports it directly" -- it is in the list because something you depend on needs it, and go mod tidy maintains those lines. replace and exclude are honoured only when the file belongs to the main module; if a library you depend on has a replace in its go.mod, the go command ignores it completely.
Technical Depth: Selection, Verification, Versions
Minimal Version Selection, worked through
Suppose the main module requires A v1.2.0 and B v1.4.0, and that:
A v1.2.0 requires C v1.1.0
B v1.4.0 requires C v1.3.0
C v1.5.0 exists on the proxy
| Module | Minimum asked for | By |
|---|---|---|
| C | v1.1.0 | A v1.2.0 |
| C | v1.3.0 | B v1.4.0 |
| C selected | v1.3.0 | highest minimum, not highest published |
C v1.5.0 is not used, even though it exists and is compatible. Nothing upgrades behind your back: to move to it you write go get example.com/C@v1.5.0, which adds an explicit require to your go.mod, making you the module asking for the higher minimum. Equally, dropping B does not immediately downgrade C -- the requirement stays until go mod tidy recomputes the graph. Upgrades are therefore always a recorded, reviewable change to a file, which is the entire design goal.
go.sum and the checksum database
go.sum records hashes for every module version the graph mentions, not just the ones selected, so a future selection change is still verifiable. On first download the go command checks the hash against the public checksum log at sum.golang.org, then against go.sum; a mismatch is a hard failure, not a warning. Commit go.sum. Delete a line by hand and the next build fails; run go mod tidy and it is rebuilt correctly.
| Variable | Purpose |
|---|---|
GOPROXY | Where to fetch modules; defaults to https://proxy.golang.org,direct |
GOSUMDB | The checksum log, sum.golang.org by default |
GOPRIVATE | Glob patterns that bypass both proxy and sumdb, for internal repos |
GOMODCACHE | The download cache, read-only on disk; clear with go clean -modcache |
GOFLAGS | Default flags, e.g. -mod=readonly |
GOTOOLCHAIN | auto fetches the toolchain a module asks for; local refuses to |
Version strings
| Form | Meaning |
|---|---|
v1.6.0 | A published semver tag |
v0.0.0-20260115093000-a1b2c3d4e5f6 | Pseudo-version: no earlier tag exists |
v1.2.4-0.20260115093000-a1b2c3d4e5f6 | Pseudo-version above the tag v1.2.3 |
v2.0.0+incompatible | A repo tagged v2 or higher that has no go.mod |
Pseudo-versions are ordinary versions to MVS: they sort below the release they precede, which is why an untagged commit never accidentally outranks a real tag.
Semantic import versioning
Major versions 0 and 1 use the plain module path. Major version 2 and above must put the major in the path, both in go.mod and in every import:
module example.com/slugger -> import "example.com/slugger"
module example.com/slugger/v2 -> import "example.com/slugger/v2"
This is not bookkeeping. Because the paths differ, the two majors are different modules, so one program can depend on both -- which is how a large codebase migrates incrementally instead of in one commit. Publish either from a v2/ subdirectory or from a branch whose go.mod carries the /v2 path.
The commands, by job
| Command | What it does |
|---|---|
go mod init path | Creates go.mod with the given module path |
go mod tidy | Adds what is imported, removes what is not, rewrites go.sum |
go get pkg@v1.2.3 | Changes a requirement in go.mod; does not install binaries |
go install pkg@v1.2.3 | Builds a command into GOBIN, ignoring the current go.mod |
go run pkg@v1.2.3 | Runs a tool once without installing it |
go mod why -m mod | Prints the import chain that explains a requirement |
go mod graph | The full requirement graph, one edge per line |
go list -m -u all | Every selected module plus the newest available |
go mod verify | Rechecks the cache against go.sum |
go mod vendor | Copies dependencies into vendor/, used automatically if present |
Since Go 1.16 the default is -mod=readonly: a build that would need to change go.mod fails and tells you which command to run, so compiling can never silently alter your dependency list.
Workspaces
go.work (Go 1.18) lets several modules on disk be developed together. Its use lines override every matching require in the whole build, which makes the old replace ../lib trick unnecessary -- and unlike replace, a workspace file is local, so there is nothing to remember to strip out before publishing.
Real World Example: A Workspace With Two Majors In One Build
A library being migrated, its consumer, and both majors linked into the same binary -- developed locally with a workspace so no replace line ever exists.
work/
go.work
slugger/
go.mod module example.com/slugger
slug.go
v2/
go.mod module example.com/slugger/v2
slug.go
site/
go.mod module example.com/site
main.go
// slugger/slug.go -- module example.com/slugger
package slugger
import "strings"
// Make joins the alphanumeric runs of s with single hyphens.
func Make(s string) string {
var b strings.Builder
sep := false
for _, r := range strings.ToLower(s) {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
if sep && b.Len() > 0 {
b.WriteByte('-')
}
sep = false
b.WriteRune(r)
default:
sep = true
}
}
return b.String()
}
// slugger/v2/slug.go -- module example.com/slugger/v2
package slugger // the package name is unchanged; only the module path gained /v2
import "strings"
// Make takes a maximum length and truncates on a word boundary. The new
// parameter is a breaking change, which is exactly what makes this v2.
func Make(s string, max int) string {
out := scan(s)
if max <= 0 || len(out) <= max {
return out
}
out = out[:max]
if i := strings.LastIndexByte(out, '-'); i > 0 {
out = out[:i]
}
return strings.TrimRight(out, "-")
}
// scan is v1's algorithm, copied. Two majors are two modules; they do not
// share code unless one of them imports the other.
func scan(s string) string {
var b strings.Builder
sep := false
for _, r := range strings.ToLower(s) {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
if sep && b.Len() > 0 {
b.WriteByte('-')
}
sep = false
b.WriteRune(r)
default:
sep = true
}
}
return b.String()
}
// site/main.go -- module example.com/site
package main
import (
"fmt"
v1 "example.com/slugger"
v2 "example.com/slugger/v2"
)
func main() {
titles := []string{"Hello, World!", "Go 1.22 Release", " spaces "}
for _, t := range titles {
fmt.Printf("%-18q v1=%-16s v2=%s\n", t, v1.Make(t), v2.Make(t, 10))
}
}
site/go.mod
module example.com/site
go 1.22
require (
example.com/slugger v1.0.0
example.com/slugger/v2 v2.0.0
)
go work init ./slugger ./slugger/v2 ./site
go run ./site
Output:
"Hello, World!" v1=hello-world v2=hello
"Go 1.22 Release" v1=go-1-22-release v2=go-1-22
" spaces " v1=spaces v2=spaces
The two require lines in site/go.mod were never downloaded. go work init wrote a go.work whose use lines name all three directories, and a workspace overrides every matching requirement in the build, so example.com/slugger resolves to ./slugger on disk. Edit the library, run the consumer, see the change -- with no replace line, which matters because a replace pointing at ../slugger has to be deleted before publishing and is ignored by anyone who depends on you, making it the single most common way to ship a module nobody else can build.
Both majors are linked into one binary, and that is the entire justification for putting /v2 in the path. example.com/slugger and example.com/slugger/v2 are different module paths, therefore different modules, therefore not in conflict -- so a large caller can migrate one file at a time instead of in one irreversible commit. The package name stayed slugger in both, which is why main.go aliases the imports: the /v2 lives in the path, not in the package clause.
Note what the workspace does not change. go.mod and go.sum in each module are still the record of what a build outside the workspace will use, and go build still refuses to edit them. When the migration is finished you delete go.work, and the requirements that were sitting there unused all along become the real ones -- resolved by MVS from the published tags, verified against go.sum, byte-identical for anyone who checks out that commit in five years.
The workflow around this is small and worth internalising. go mod tidy is the only command that should be adding or removing requirements. go get pkg@version records a deliberate upgrade. go install pkg@version puts a tool on your PATH without touching the current module at all, and go run pkg@version does it without even installing. A go.work file belongs in .gitignore for a normal library or service, and gets committed only when the repository genuinely is a multi-module workspace that everyone should build the same way.
Common Mistakes
- Publishing with a
replacestill ingo.mod. It works for you and is ignored by everyone who imports you, so their build resolves a version you never tested. Use a workspace for local development instead. - Assuming the newest version gets used. MVS selects the highest minimum in the graph. If you want
v1.5.0, ask for it withgo get; nothing will drift there on its own. - Expecting
go getto install a command. It edits requirements. Installing a tool isgo install example.com/tool@latest, which deliberately ignores the current module. - Publishing a breaking change without the
/v2path. Consumers on v1 get the break on their next upgrade, and no import can distinguish the two. The major version belongs in the module path. - Hand-editing a version in
go.modand notgo.sum. The next build fails verification. Change versions withgo getand letgo mod tidyreconcile the sums. - Not committing
go.sum, or committingvendor/by accident.go.sumis the only thing making the build verifiable;vendor/is a deliberate choice that then silently takes over every build. - Deleting
// indirectlines by hand. They are load-bearing: they record minimums that the graph needs.go mod tidyis what removes the ones that are genuinely unnecessary. go get -u ./...as routine hygiene. It raises the minimum of the entire transitive graph in one commit. Upgrade the dependency you mean to upgrade, and read its changelog.- Vendoring a fork by rewriting import paths. Every file in your codebase then names your fork. A single
replaceline in the main module does the same job reversibly. - Setting
gohigher than the toolchain your CI has. WithGOTOOLCHAIN=localthat is a hard failure; setting it lower while using newer language features fails in the opposite direction. - Committing
go.workin a library. Everyone who clones it then builds against whatever directories happen to be listed, instead of the published requirements.
Best Practices
- Choose the module path from the URL people will actually fetch it from, because it is both the import prefix and the download location.
- Let
go mod tidyown the requirement list, and treat any diff it produces as something to read rather than something to accept blindly. - Upgrade one dependency at a time with
go get pkg@version, so the commit history records exactly which bump changed behaviour. - Commit
go.modandgo.sum; leavego.workuntracked unless the repository is genuinely a workspace. - Set
GOPRIVATEfor internal module prefixes so private code never reaches the public proxy or checksum database. - Keep the
godirective at the oldest version you actually support, and raise it deliberately when you want a language feature such as per-iteration loop variables. - Use
go mod why -mbefore removing anything from the graph -- it prints the import chain that explains why a module is there. - Pin tools with
go install tool@v1.2.3in a script or Makefile rather than@latest, so a build machine cannot pick up a different tool than a developer.
Practice Exercises
- Trace a selection by hand. Given a main module requiring
A v1.1.0andB v1.2.0, where A needsC v1.4.0and B needsC v1.2.0, write down the selected version of C, then the effect of addingrequire C v1.6.0to the main module, then the effect of removing B. - Break and repair verification. Create a module with one dependency, delete a line from
go.sum, record the exact error fromgo build, then repair it withgo mod tidyand confirm the line comes back identical. - Build a workspace. Make two local modules where one imports the other, wire them with
go work init, change a function in the library and confirm the consumer sees it without anyreplaceline. Then deletego.workand record what breaks. - Ship a v2. Take a small library, make one breaking signature change, publish it as
/v2from av2/subdirectory, and write a program that imports both majors with aliases and calls each. Confirmgo mod graphlists them as two separate modules.