Toolchain, Modules & Packages: go run/build, go.mod, exports, init, main
"A module is a collection of packages that are released, versioned, and distributed together." — Go Modules Reference, go.dev/ref/mod
Summary: A Go program is a tree of packages inside a module; the go command resolves the module graph with minimal version selection, verifies it with go.sum, compiles it with a toolchain your go.mod can pin, and the only visibility rule is the capital letter. Focus: go run/build/install/test/vet/fmt/mod/get/work/env/doc/generate, go.mod directives, go.sum and the checksum database, proxies and private modules, /v2 import paths, workspaces, exported identifiers and internal/, init() and main, build tags, cross-compilation, -ldflags -X, -trimpath, reproducible builds and runtime/debug.ReadBuildInfo. Learning goal: Given any "cannot find module providing package", "missing go.sum entry" or "import cycle not allowed", say which file or directory is wrong and fix it, and ship two stamped, cross-compiled, reproducible binaries from one module.
This page owns the mechanics of the go command, the module system and the package system. It does not teach directory conventions for large services, linters, Makefiles or Docker images (that is Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds); it does not teach how to write tests (that is Testing & Benchmarking) or flag parsing and logging (that is CLI Flags, Subcommands, Environment Variables & Logging). Container image mechanics are in Containers & Kubernetes. Every output block below was produced with Go 1.27.4 on macOS arm64 unless it says "expected, not run"; the documentation read for the rules is the Go 1.24/1.25 release notes and the module reference on go.dev.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why modules, why a toolchain line | Why it exists |
| GOPATH, vgo, Go 1.11 to 1.21 | Where it comes from |
Which Go version runs, GOTOOLCHAIN | Installing and choosing a toolchain |
go run, build, install, test, vet, fmt, doc, generate | The go command |
module, go, toolchain, require, replace, exclude, retract | go.mod |
missing go.sum entry, checksum database | go.sum and the checksum database |
GOPROXY, GOPRIVATE, GONOSUMDB, GOFLAGS | Proxies and private modules |
v2, v0.0.0-2025...-abcdef123456, +incompatible | Versions |
| Which version does Go pick | Minimal version selection |
go get, go mod tidy, vendor, why, graph | Managing dependencies |
| Working on two modules at once | Workspaces |
| Directory versus package versus module | Packages |
Capital letters, internal/ | Exported identifiers and internal packages |
init(), blank imports | init and package initialisation |
package main, cmd/ | main and multiple binaries |
//go:build, _linux.go | Build tags |
GOOS, GOARCH, CGO_ENABLED | Cross-compilation |
-ldflags -X, -trimpath, reproducibility | Stamping and reproducible builds |
ReadBuildInfo, go version -m | Build information |
go env, GOMODCACHE | The environment and the module cache |
| Exact error texts | Error texts decoded |
| Fixes for common situations | Solving the classic problems |
| Composer and Laravel comparison | For PHP/Laravel developers |
| From one binary to many services | In architecture |
| Commands with real output | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The four nested units. Each row is unpacked in the concept catalogue.
| Unit | In plain words | Where it lives | Named by |
|---|---|---|---|
| Module | A versioned bundle of packages | A directory tree with go.mod at its root | The module line, for example github.com/acme/shop |
| Package | The unit of compilation and of visibility | One directory, one package name | Import path = module path + relative directory |
| File | A source file with a package clause | .go files in that directory | File name; suffixes _linux, _test mean something |
| Identifier | A function, type, variable, constant, field or method name | Inside a file | A capital first letter exports it |
The files you will meet.
| File | Who writes it | What it holds | Commit it? |
|---|---|---|---|
go.mod | You and the go command | Module path, Go version, requirements, replacements | Yes |
go.sum | The go command | Cryptographic hashes of every module version used | Yes |
go.work | You, for local development | Which local modules form one workspace | Usually no |
go.work.sum | The go command | Hashes needed only in workspace mode | Same as go.work |
vendor/ and vendor/modules.txt | go mod vendor | A copy of the dependencies | Only if you vendor |
$GOROOT/go.env | The Go distribution | Default GOPROXY, GOSUMDB, GOTOOLCHAIN | No |
go env file (os.UserConfigDir()/go/env) | go env -w | Your per-user defaults | No |
The commands.
| Command | What it does | Writes a binary? | Typical use |
|---|---|---|---|
go run ./cmd/api | Compile to a temp directory and execute | No (temp) | Development loop |
go build ./... | Compile; discard results for libraries, keep the binary for one main with -o | With -o or one main in cwd | CI compile check, release builds |
go install ./cmd/api | Compile and place in $GOBIN (default $GOPATH/bin) | Yes, installed | Tools for your machine |
go test ./... | Compile test binaries and run them | No | Tests |
go vet ./... | Static checks for suspicious code | No | CI gate |
gofmt -l . / go fmt ./... | List or rewrite non-canonical formatting | No | CI gate, editor save |
go mod tidy | Add missing, drop unused requirements, fix go.sum | No | After every import change |
go get pkg@v1.2.3 | Add, upgrade or downgrade one requirement | No | Dependency changes |
go work init ./a ./b | Create a workspace | No | Multi-module development |
go env GOPROXY | Print configuration | No | Debugging |
go doc fmt.Println | Print documentation from source | No | Offline reference |
go generate ./... | Run //go:generate commands | No | Codegen before build |
Why it exists
Source code has to be found, versioned, verified and compiled the same way on every machine. Before modules, Go found everything under one global directory (GOPATH), had no versions and no lock file, and every team invented a vendoring tool. The module system answers four questions with four files and one algorithm.
| Question | Answered by | What you pay |
|---|---|---|
| Which code is "mine"? | The module line and the directory tree under go.mod | A module path you can never casually change |
| Which versions do I need? | require plus minimal version selection | Upgrades are explicit; nothing moves by itself |
| Is the code I downloaded the code everyone else got? | go.sum plus the checksum database | An extra network call the first time |
| Which compiler builds it? | The go and toolchain lines plus GOTOOLCHAIN | A download on first use of a newer toolchain |
The picture to keep: a shipping container. A module is the container with a manifest (go.mod), a tamper seal (go.sum) and a label with the owner's address (the module path); packages are the boxes inside; the capital letter is the sticker that says "may be opened by the customer"; and internal/ is the box marked "staff only".
Three common misunderstandings, up front
- "A package is a file" or "a module is a package". A package is a directory of files that share a
packageclause; a module is a tree of packages with onego.mod. - "
go.sumis the lock file". It is not. The build list is recomputed fromgo.modby minimal version selection every time;go.sumonly proves that the bytes match. - "
go 1.24ingo.modis the version I build with". Since Go 1.21 it is a minimum, and the language version the compiler enforces for that module; the toolchain that actually runs may be newer or may be downloaded.
Where it comes from
| Year / version | What changed | Why it matters now |
|---|---|---|
| Go 1.0 to 1.10 | go get clones into $GOPATH/src; no versions | Old tutorials still say "put it in GOPATH" |
| 2018 | Russ Cox's Minimal Version Selection design (cited by the module reference) | The algorithm is still the one in use |
| Go 1.11 (2018) | Preliminary module support, outside $GOPATH/src | go.mod and go.sum appear |
| Go 1.13 (2019) | Module mode is the default; module mirror and checksum database are default | GOPROXY and GOSUMDB defaults |
| Go 1.16 (2021) | -mod=readonly is the default: builds never edit go.mod | You must run go mod tidy or go get yourself |
| Go 1.18 (2022) | Workspaces (go.work); binaries embed version-control information | Multi-module development, vcs.revision |
| Go 1.19 (2022) | The unix build constraint | One tag for all Unix-like systems |
| Go 1.21 (2023) | go line is a strict minimum; toolchain line; automatic toolchain download | GOTOOLCHAIN exists |
| Go 1.24 (2025) | tool directive and go get -tool; go tool runs module-pinned tools | Replaces the tools.go blank-import trick |
| Go 1.25 (2025) | ignore directive in go.mod | Directories that ./... skips |
The Go 1.21 release notes say that earlier releases treated the go line as advisory and that 1.21 now reads it as a minimum requirement; the module blog post "Using Go Modules" says that as of Go 1.13 module mode is the default for all development; the module mirror announcement says the mirror and checksum database are production ready for Go 1.13 users. Sources are listed in References.
The concept catalogue
Installing and choosing a toolchain Must-know
In plain words: The go command you type is a launcher. It reads your go.mod, and if your module asks for a newer Go than the one installed, it downloads that toolchain into the module cache and runs it for you.
Common misunderstanding: "I must install every Go version by hand (or use a version manager) for each project." Since Go 1.21 the installed go command can fetch the toolchain a module needs, unless you turn that off.
Definition: The go directive (the "go directive" in the module reference) sets the minimum Go version for the module and the language version the compiler enforces for its packages. The optional toolchain directive (the "toolchain directive") suggests a specific toolchain. GOTOOLCHAIN chooses between the bundled toolchain (local), a specific one (go1.24.3), or switching (auto, shorthand for local+auto; path, shorthand for local+path). The go.dev toolchain document states that "The Go toolchain refuses to load a module or workspace that declares a minimum required Go version greater than the toolchain's own version" when switching is disabled.
1 go.mod says: go 1.24.0 toolchain go1.24.3
2 go on PATH is: go1.23.1
3 GOTOOLCHAIN=auto -> 1.23.1 < 1.24.3, download golang.org/toolchain@go1.24.3 into GOMODCACHE
4 go command re-executes itself as go1.24.3
5 go version -> go version go1.24.3 linux/amd64Real scenario: A team pins go 1.24.0 in every service; a new hire installs whatever is current, and the first go build downloads the exact toolchain. A regulated build farm sets GOTOOLCHAIN=local so nothing is downloaded and an old toolchain fails loudly. A CI image bakes in GOTOOLCHAIN=path so a mismatch fails instead of fetching.
GOTOOLCHAIN value | Behaviour | Use it when |
|---|---|---|
auto (default in standard distributions) | Same as local+auto: use the bundled toolchain unless go.mod needs newer, then download | Developer laptops |
local | Always the bundled toolchain; refuse modules that need newer | Hermetic or air-gapped builds |
go1.24.3 | Always that toolchain | Reproducing a bug on an exact version |
go1.24.3+auto | At least 1.24.3; switch further if go.mod says so | A team-wide floor |
path / local+path | Look for a goX.Y.Z binary on PATH; never download | Pre-installed toolchains in CI |
Fix / how to use it:
go version # which go am I?
go env GOTOOLCHAIN # auto
go env -w GOTOOLCHAIN=local # persist for your user (go env file)
GOTOOLCHAIN=go1.24.3 go test ./... # one command on a chosen version
go get go@1.24.3 # raise the go line (and toolchain if needed)The go line of a dependency can force yours up: a module's go line must be at least as high as the go line of every module it requires. A go.mod with no go line is treated as go 1.16.
The go command tour Must-know
In plain words: One binary, many verbs. Most days you use six: run, build, test, vet, fmt, mod tidy.
Common misunderstanding: "go build produces a binary for any package." For a library package it only checks that it compiles and throws the result away; only package main produces an executable. go run example.com/nm on a non-main package fails with package example.com/nm is not a main package.
Definition: Each verb takes package patterns: . (the current directory), ./cmd/api (a directory), ./... (this directory and everything below, except directories starting with . or _, named testdata, or listed in an ignore directive since Go 1.25), or an import path.
1 go run ./cmd/hello -name Ada # compile into a temp dir, run, delete
2 go build -o bin/hello ./cmd/hello # compile, keep the binary
3 go install ./cmd/hello # compile, copy to $GOBIN or $GOPATH/bin
4 go test ./... -run TestX -count=1 # compile test binaries, run them, bypass the test cache
5 go vet ./... # printf mismatches, copied locks, unreachable codeReal scenario: CI runs gofmt -l . (must print nothing), go vet ./..., go test -race ./..., then go build ./.... A release job runs go build -trimpath -ldflags ... per binary. A developer uses go doc net/http.Client without leaving the terminal.
| Verb | Flags worth knowing | What it will not do |
|---|---|---|
go run | -race, -tags x, arguments after the package | Keep the binary |
go build | -o, -trimpath, -ldflags, -tags, -race, -buildvcs=false, -v, -x | Install anything |
go install | pkg@version (outside any module) | Edit go.mod when given @version |
go test | -run, -v, -count=1, -race, -cover, -short, -tags | Run //go:build ignore files |
go vet | -printf=false and per-analyser switches | Find races or logic bugs |
go fmt / gofmt | gofmt -l, -d, -w, -s | Reorder imports across groups beyond sorting |
go doc | go doc pkg.Symbol, -all, -src | Fetch network docs |
go generate | -run regexp, -n | Run automatically during build |
go list | -m all, -deps, -f template, -json | Change files |
go clean | -cache, -modcache, -testcache | Touch your source |
go generate scans for lines such as //go:generate stringer -type=State and runs them in the package directory; the generated files are committed, so the build itself never needs the generator. Since Go 1.24 go tool stringer can run a tool pinned by a tool directive.
go.mod: module, go, toolchain, require, replace, exclude, retract Must-know
In plain words: go.mod is the module's identity card and shopping list: its name, the Go it needs, and the minimum version of each dependency.
Common misunderstanding: "The module path must be a URL I can fetch." It must be unique and, if anyone will go get it, resolvable; for an application nobody imports, module shop or module example.com/shop works, but a public path that matches a repository is the safe habit.
Definition: go mod init <path> writes the first line. Every package import path in the module starts with the module path. The directives:
| Directive | Meaning | Who may use it |
|---|---|---|
module | The module path (with /v2 suffix from major 2 on) | Every module |
go | Minimum Go version and language version | Every module |
toolchain | Suggested toolchain, only a floor | Optional |
godebug | Sets GODEBUG defaults (default=go1.24, panicnil=1) | Main module (Go 1.23+) |
require | Minimum version of a dependency; // indirect marks ones you do not import directly | Every module |
replace | Swap a module (or one version) for another module or a local directory | Main module only |
exclude | Forbid one exact version | Main module only |
retract | Say that versions you published must not be used | The publisher, in the newer version |
tool | Pin an executable dependency for go tool (Go 1.24+) | Main module |
ignore | Directories the ./... pattern skips (Go 1.25+) | Main module |
Only the main module's replace and exclude count; those in dependencies are ignored. That is why a library cannot fix your build with a replace.
// go.mod of an application (illustrative; versions are examples)
module github.com/example/shop // module path: import-path prefix of every package here
go 1.24.0 // minimum Go version needed to build; also the language version
toolchain go1.24.3 // suggested toolchain; only a floor, never a ceiling
godebug default=go1.24 // pin runtime behaviour defaults (Go 1.23+)
require (
github.com/jackc/pgx/v5 v5.7.2 // /v5 is part of the import path (semantic import versioning)
golang.org/x/sync v0.10.0
example.com/legacy v1.2.3 // indirect // required by a dependency, recorded for reproducibility
)
tool golang.org/x/tools/cmd/stringer // Go 1.24: executable dependency run with `go tool stringer`
replace example.com/legacy => ../legacy // local checkout while debugging
replace golang.org/x/sync v0.10.0 => golang.org/x/sync v0.9.0 // pin one version elsewhere
exclude golang.org/x/net v0.19.0 // never select this exact version
retract ( // only meaningful in a module you publish
v1.0.1 // published by mistake; do not use
[v1.1.0, v1.1.4] // broken range
)Real scenario: You fork a library to patch a bug: replace github.com/acme/lib => ../lib-fork while you test, then replace github.com/acme/lib => github.com/you/lib v1.4.1-fix in the commit that ships. A vulnerable release v1.3.0 of your own library is retracted with retract v1.3.0 // CVE fix in 1.3.1; go list -m -u and go get then warn consumers.
What provides it: go mod init, go mod edit (scriptable edits: go mod edit -require=example.com/lib@v0.0.0 -replace=example.com/lib=../lib), go get and go mod tidy.
go.sum and the checksum database Must-know
In plain words: go.sum is a list of fingerprints. If a download does not match its fingerprint, the build stops.
Common misunderstanding: "go.sum pins versions like package-lock.json." Versions come from go.mod. go.sum has two lines per module version: a hash of the module's whole content (h1: of the zip) and a hash of just its go.mod file (/go.mod h1:). Extra lines are normal.
Definition: The first time a module version is needed, the go command asks the checksum database (default GOSUMDB=sum.golang.org), a transparent Merkle-tree log, for the expected hash, compares it to the downloaded bytes and appends it to go.sum. Later builds compare against go.sum alone. The module mirror announcement says the checksum database "is a global source of go.sum lines" that lets everyone see the same bytes.
1 go get golang.org/x/text@v0.44.0 # fetch via GOPROXY
2 go -> sum.golang.org # ask: what is the hash of this version?
3 go compares proxy bytes with the answer, writes two lines to go.sum
4 next build (any machine) checks the module cache against go.sum
5 mismatch -> "SECURITY ERROR: verifying module: checksum mismatch"Real scenario: A CI job reports missing go.sum entry after a developer forgot to commit go.sum; another fails with a checksum mismatch because a maintainer re-tagged a version (never re-tag; use a new version). go mod verify re-hashes the module cache against go.sum.
| Situation | What go does | Command to fix |
|---|---|---|
| Hash missing | missing go.sum entry for module providing package ... | go mod tidy or go get <module> |
| Hash different | verifying module: checksum mismatch | Investigate; never just delete the line |
| Private module | Skip the checksum database via GOPRIVATE / GONOSUMDB | Set the variable |
| Offline | GOFLAGS=-mod=mod cannot help; use vendor/ or a proxy | go mod vendor |
| Old lines | Harmless | go mod tidy prunes unused ones |
Proxies and private modules: GOPROXY, GOPRIVATE, GONOSUMDB, GOFLAGS Important
In plain words: By default the go command downloads from Google's module mirror, not from GitHub, and checks the answer against a public log. For private code you tell it not to leak your module paths to either.
Common misunderstanding: "go get clones the repository." With the default GOPROXY=https://proxy.golang.org,direct it fetches zip files over HTTPS from the proxy first and only falls back to direct (version control) when the proxy says 404 or 410.
Definition: The variables:
| Variable | Default | Meaning |
|---|---|---|
GOPROXY | https://proxy.golang.org,direct | Comma- or pipe-separated list of proxies; direct means VCS; off forbids network |
GOSUMDB | sum.golang.org | Checksum database; off disables verification |
GOPRIVATE | empty | Glob list of module path prefixes that are private: implies GONOPROXY and GONOSUMDB |
GONOPROXY | GOPRIVATE | Paths fetched directly, never via a proxy |
GONOSUMDB | GOPRIVATE | Paths not looked up in the checksum database |
GOINSECURE | empty | Paths allowed over plain HTTP or unverified TLS |
GOVCS | public:git|hg,private:all | Which version-control tools may be used for which hosts |
GOFLAGS | empty | Default flags for every go command, -mod=vendor, -modcacherw |
GOMODCACHE | $GOPATH/pkg/mod | Where downloads are unpacked |
$ go env -w GOPRIVATE='git.example.com/*'
$ go env GOPRIVATE GONOPROXY GONOSUMDB GOPROXY
git.example.com/*
git.example.com/*
git.example.com/*
https://proxy.golang.org,direct
$ go env -w GOFLAGS=-count=1 ; go env GOFLAGS ; go env -u GOFLAGS
-count=1Real scenario: A company runs an Artifactory or Athens proxy: GOPROXY=https://goproxy.corp.example,https://proxy.golang.org,direct, GOPRIVATE=git.corp.example.com. Private repositories need git credentials (~/.netrc or git config url."ssh://git@...".insteadOf), because direct shells out to git.
Versions: semantic versioning, pseudo-versions, /v2 Must-know
In plain words: Versions look like v1.4.2. A major version 2 or higher is a different module, so its path changes to .../v2 and you can use v1 and v2 side by side.
Common misunderstanding: "I can tag v2.0.0 on my repo and users get it with go get." Without /v2 in the module line and in every import, the tag is rejected (or shows up as +incompatible if the repository never had a go.mod).
Definition: Semantic import versioning: the import compatibility rule says a package with the same import path must stay backward compatible, so a breaking change needs a new path. Forms of version:
| Form | Example | Meaning |
|---|---|---|
| Release | v1.4.2 | A tagged commit |
| Pre-release | v1.5.0-rc.1 | Sorted before v1.5.0 |
| Pseudo-version | v0.0.0-20191109021931-daa7c04131f5 | An untagged commit: base + UTC commit time + 12-character hash |
| Pseudo after a tag | v1.2.4-0.20191109021931-daa7c04131f5 | Untagged commit after v1.2.3 |
+incompatible | v2.1.0+incompatible | A v2+ tag in a repository without go.mod |
| Queries | @latest, @v1, @none, @master, @abc1234 | Accepted by go get; resolved to one of the above |
v0.x.y | v0.3.1 | No compatibility promise |
module github.com/acme/lib/v2 // in the v2 go.mod
import "github.com/acme/lib/v2/store" // every importer writes /v2Two layouts publish v2: a major branch (one directory, change the path on the v2 branch) or a major subdirectory (/v2 directory with its own go.mod on the default branch); the go.dev "Go Modules: v2 and Beyond" post describes both.
Real scenario: gopkg.in/yaml.v3, github.com/jackc/pgx/v5 and github.com/go-chi/chi/v5 are all v2+ and carry the suffix in the path. A service can import lib/v1 and lib/v2 during a migration because they are different packages.
Minimal version selection Must-know
In plain words: Go picks, for each dependency, the highest version that anyone in your graph asked for, and nothing newer, even if newer exists.
Common misunderstanding: "Go installs the latest compatible version like npm or Composer." It chooses the minimum version that satisfies every require; a new release of a dependency changes nothing until someone raises a requirement.
Definition: MVS builds a graph from the go.mod files, takes the maximum required version of each module, and calls the result the build list. The module reference says the build list is not saved in a lock file because "MVS is deterministic, and the build list doesn't change when new versions of dependencies are released".
1 main requires A >= 1.2, B >= 1.2
2 A 1.2 requires C >= 1.3 B 1.2 requires C >= 1.4
3 C 1.3 and C 1.4 both require D >= 1.2
4 highest required: A 1.2, B 1.2, C 1.4, D 1.2 <- the build list
5 go list -m all # prints itReal scenario: Library authors raise requirements only when they need a fix, so your build is stable between go get -u runs. Security patch: go get golang.org/x/net@v0.40.0 raises the requirement; everything that depends on x/net gets at least that.
Fix / how to use it: go get -u ./... raises direct and indirect requirements to the latest minor/patch; go get -u=patch only patches; go get pkg@none drops one; go list -m -u all lists available upgrades; go mod graph and go mod why -m explain why a version is selected.
Managing dependencies: get, tidy, vendor, why, graph Must-know
In plain words: Edit imports freely, then run go mod tidy; it makes go.mod and go.sum match what the code really imports.
Common misunderstanding: "go build will add the dependency for me." Since Go 1.16 it will not; it prints no required module provides package ...; to add it: go get ....
Definition and sequence:
1 edit main.go: import "golang.org/x/text/language"
2 go build ./... -> main.go:6:2: no required module provides package golang.org/x/text/language; to add it:
3 -> go get golang.org/x/text/language
4 go mod tidy -> go: found golang.org/x/text/language in golang.org/x/text v0.44.0
5 git add go.mod go.sum| Command | Effect | Notes |
|---|---|---|
go get pkg@v1.2.3 | Set the requirement to exactly that version (up or down) | @latest is the default query |
go get -u ./... | Upgrade dependencies of the packages | -u=patch for patch only |
go get -tool pkg | Add a tool directive (Go 1.24) | Run with go tool name |
go mod tidy | Add missing and remove unused requirements and sums | Considers tests of the main module's packages |
go mod download | Fill the module cache; -x shows the commands | Warm CI caches |
go mod verify | Re-hash the module cache against go.sum | Detects local tampering |
go mod vendor | Copy needed packages to vendor/ and write vendor/modules.txt | Then -mod=vendor is automatic when go 1.14+ |
go mod why -m x | Shortest import chain from your main module to x | Answers "why is this here?" |
go mod graph | Print module requirements, one edge per line | Feed to grep, dot |
go list -m all | Print the build list | After MVS |
go mod edit | Scriptable edits and -json output | For tooling |
Real scenario: A supply-chain review asks why golang.org/x/tools is in your build; go mod why -m golang.org/x/tools prints the chain. A CI sandbox with no internet builds with go build -mod=vendor ./....
Replace, exclude and retract in practice Important
In plain words: replace says "use this other code instead", exclude says "never that exact version", retract says "I, the author, regret that version".
Common misunderstanding: "I can leave replace ../lib in a commit." It is only honoured in the main module, so it works on your machine and for no one who imports your module; and it breaks CI where ../lib does not exist.
Definition: replace old[@v] => new[@v] swaps one module version or every version; => ./dir needs a go.mod inside; exclude removes one version from the graph so MVS picks the next higher required; retract is written in the newer version's go.mod and marks lower versions (or a range [v1.1.0, v1.1.4]) as withdrawn.
| Directive | Scope | Lifetime | Best for |
|---|---|---|---|
replace => ../local | Main module only | While debugging | Editing a dependency alongside |
replace => fork vX | Main module only | Until upstream merges | Patching a bug |
exclude | Main module only | Until a fixed version exists | A known bad release |
retract | Publisher | Forever (history) | A tag you published by mistake |
go work use | Your workspace | Local only | Replacing many replaces |
Workspaces: go.work Important
In plain words: A workspace lets several local modules see each other without editing any go.mod.
Common misunderstanding: "Workspace mode changes what my teammates build." go.work is not read from inside your dependencies, and CI that sets GOWORK=off ignores it; do not rely on it for the published build.
Definition: go work init ./app ./lib writes go.work with use directives. In workspace mode all used modules are main modules, versions are chosen by MVS across them, and replace in go.work applies to all. go env GOWORK shows the active file; GOWORK=off disables it.
go 1.24.0
use (
./app
./lib
)
// replace works here too and applies to every module in the workspace.
// go.work and go.work.sum are local development files: do not commit them
// unless your team agrees to; CI should build with GOWORK=off.Real scenario: Service shop and library shop-money live in two repositories; you change both for one feature. With a go.work that uses both directories, go test ./... in shop sees your uncommitted shop-money. Before the PR, you publish shop-money, bump the requirement in shop/go.mod, and delete the workspace file locally.
Packages versus directories Must-know
In plain words: One directory is one package. Every .go file there starts with the same package name line, and the import path is the module path plus the directory path.
Common misunderstanding: "The package name must match the directory name." It conventionally does, but the compiler requires only that files in one directory agree; the name you write in code is the package clause, not the last path element (github.com/x/chi/v5 is package chi).
Definition: A package is a set of files in one directory with the same package clause (plus an optional _test external test package). Test files end in _test.go; a package greet_test in the same directory is a different package that can import greet and sees only its exported API.
1 academy/shop module root (go.mod: module academy/shop)
2 academy/shop/cmd/api package main -> binary api
3 academy/shop/internal/orders package orders import path: academy/shop/internal/orders
4 academy/shop/pkg/money package money
5 academy/shop/internal/orders/testdata ignored by ./... and by the compilerWhat provides it: Directory names beginning with . or _ and testdata are ignored by ./...; a nested directory with its own go.mod is a different module and is excluded from the parent. Import cycles are forbidden: see Error texts decoded.
Exported identifiers and internal packages Must-know
In plain words: A name that starts with a capital letter can be used from other packages; a lowercase name cannot. A directory called internal can be imported only by code in its parent tree.
Common misunderstanding: "private and public keywords are missing, so Go has no encapsulation." It has two levels: package-level via capitalisation and module-boundary-level via internal/.
Definition: The Go specification says an identifier is exported if the first character is a Unicode upper-case letter and it is declared in the package block or is a field or method name. The import path rule: a package a/b/internal/c may be imported only by code rooted at a/b.
// Package greet shows what is exported and what is not. Only identifiers that
// start with an upper-case letter are visible to other packages.
package greet
import "strings"
// Greeter is exported: other packages can name the type.
type Greeter struct {
Name string // exported field
prefix string // unexported field: invisible outside this package
}
// New is the constructor; it is the only way to set prefix from outside.
func New(name string) *Greeter {
return &Greeter{Name: name, prefix: "Hello"}
}
// Hello is an exported method.
func (g *Greeter) Hello() string {
return g.prefix + ", " + clean(g.Name) + "!"
}
// clean is unexported: a helper nobody outside can depend on.
func clean(s string) string {
return strings.TrimSpace(s)
}package greet_test
import (
"testing"
"academy/toolchain-modules-packages/internal/greet"
)
// An external test package (greet_test) sees only the exported API, exactly
// like a real importer. g.prefix would not compile here.
func TestExportedSurfaceOnly(t *testing.T) {
g := greet.New("Grace")
g.Name = "Grace Hopper"
if got := g.Hello(); got != "Hello, Grace Hopper!" {
t.Fatalf("Hello = %q", got)
}
}| Visibility tool | Boundary | Enforced by | Error |
|---|---|---|---|
| Capital letter | Package | Compiler | undefined: strings.toLower (but have ToLower) |
internal/ directory | Module subtree | go command | use of internal package ... not allowed |
| Unexported field | Package | Compiler | g.prefix undefined (type *greet.Greeter has no field or method prefix) |
_test package | Test code | Compiler | Only exported API compiles |
| Separate module | Version contract | Semantic import versioning | Breaking change needs /v2 |
Real scenario: Put everything you do not want to support under internal/; the go.dev module layout guide recommends this for supporting packages "since other projects cannot import code from our internal directory, we're free to refactor its API". Layout decisions beyond this are in Project Layout.
init and package initialisation Important
In plain words: Before main starts, Go sets up every imported package: first their variables, then their init() functions. You never call init().
Common misunderstanding: "init() order between files is something I can control by naming." It is the order the files were presented to the compiler (the go tool sorts by file name), and between packages only dependencies are guaranteed; both are easy to break.
Definition: The specification says the package is initialised "by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler". Imported packages are initialised before the importer, once each; independent packages are taken in import-path order since Go 1.21. Variables are initialised in dependency order, not source order. A package may have many init functions; none can be referenced.
// Package initorder makes Go's initialisation order observable: imported
// packages first, then package-level variables in dependency order, then
// every init() in the order the files were presented to the compiler.
package initorder
// Trace records the steps in the order they ran.
var Trace []string
func record(s string) string {
Trace = append(Trace, s)
return s
}
// a depends on b, so b is initialised first even though a is declared first.
var a = record("var a (needs b: " + b + ")")
var b = record("var b")
func init() { record("init #1 in initorder.go") }
func init() { record("init #2 in initorder.go") }package initorder
var c = record("var c in second.go")
func init() { record("init in second.go") }package initorder
import (
"reflect"
"testing"
)
func TestInitOrder(t *testing.T) {
// Files are sorted by name by the go tool, so initorder.go precedes second.go.
// b must precede a because a's initialiser mentions b; c is independent.
want := []string{
"var b",
"var a (needs b: var b)",
"var c in second.go",
"init #1 in initorder.go",
"init #2 in initorder.go",
"init in second.go",
}
if !reflect.DeepEqual(Trace, want) {
t.Fatalf("init order\n got: %q\nwant: %q", Trace, want)
}
}1 runtime starts, single goroutine for initialisation
2 initialise imported packages (each once, depth first, then by import path)
3 initialise this package's variables: b, then a (a mentions b), then c
4 run init() functions in file order: initorder.go #1, #2, then second.go
5 main.main()Real scenario: database/sql drivers register in init(); you write import _ "github.com/jackc/pgx/v5/stdlib" so the driver exists before sql.Open("pgx", ...). image/png does the same for image.Decode. The internal/registry snippet is the same pattern.
// Package registry is the pattern behind database/sql drivers and image
// decoders: packages register themselves from init(), and a blank import
// (import _ "...") is enough to make them available.
package registry
import "sort"
var names []string
// Register records a plugin name. It is called from init() functions.
func Register(name string) { names = append(names, name) }
// Names returns the registered names in registration order.
func Names() []string { return append([]string(nil), names...) }
// Sorted returns the names in a stable order independent of init order.
func Sorted() []string {
out := Names()
sort.Strings(out)
return out
}
// Reset clears the registry; tests use it.
func Reset() { names = nil }package alpha
import "academy/toolchain-modules-packages/internal/registry"
func init() { registry.Register("alpha") }Why to avoid it for your own code: init() cannot return an error or take arguments, so failures become panics or os.Exit; it runs in every test binary that imports the package; it hides dependencies behind a blank import; and it makes order matter. Prefer an explicit New(cfg) or Register(...) called from main. Keep init() for registration with a well-known registry, or for pure setup that cannot fail (precomputing a table).
main and multiple binaries: cmd/ Must-know
In plain words: A program starts in package main at func main(). One module can hold many package main directories, each becoming a separate binary.
Common misunderstanding: "Each service needs its own module." One module with cmd/api and cmd/worker shares code through internal/ and versions as a unit; split modules only when versioning or ownership really differ.
Definition: The linker builds a single main package with everything it imports; the specification requires func main() with no arguments and no result, and the program exits when it returns, without waiting for other goroutines. A go build ./cmd/... builds all binaries; go build -o bin/ ./cmd/... writes them with their directory names (when more than one main package matches, -o must be a directory).
// Command hello is the first of two binaries in this module. Every directory
// under cmd/ with a package main becomes one executable named after the directory.
package main
import (
"flag"
"fmt"
"os"
"academy/toolchain-modules-packages/internal/greet"
"academy/toolchain-modules-packages/internal/platform"
"academy/toolchain-modules-packages/internal/registry"
"academy/toolchain-modules-packages/internal/version"
// Blank imports run the packages' init() functions and nothing else.
_ "academy/toolchain-modules-packages/internal/plugins/alpha"
_ "academy/toolchain-modules-packages/internal/plugins/beta"
)
func main() {
showVersion := flag.Bool("version", false, "print build information and exit")
name := flag.String("name", "world", "who to greet")
flag.Parse()
if *showVersion {
fmt.Println(version.Read())
return
}
fmt.Fprintln(os.Stdout, greet.New(*name).Hello())
fmt.Println("platform:", platform.Describe())
fmt.Println("plugins:", registry.Names())
}// Command worker is the second binary: same module, same internal packages,
// a different main.
package main
import (
"fmt"
"academy/toolchain-modules-packages/internal/version"
)
func main() {
fmt.Println("worker", version.Read())
}package main
import (
"reflect"
"testing"
"academy/toolchain-modules-packages/internal/registry"
)
// The blank imports in main.go registered both plugins before any test ran,
// in the order the imports appear in the source.
func TestBlankImportsRegisterPlugins(t *testing.T) {
want := []string{"alpha", "beta"}
if got := registry.Names(); !reflect.DeepEqual(got, want) {
t.Fatalf("Names() = %v, want %v", got, want)
}
if got := registry.Sorted(); !reflect.DeepEqual(got, want) {
t.Fatalf("Sorted() = %v, want %v", got, want)
}
}Real scenario: cmd/api, cmd/worker, cmd/migrate share internal/orders. Each Docker image copies one binary (Project Layout covers the Dockerfile). go install github.com/acme/tool/cmd/tool@latest installs a published command outside any module.
Build tags and file suffixes Important
In plain words: You can tell the compiler "only compile this file on Linux" or "only when I pass -tags debug".
Common misunderstanding: "// +build or a comment anywhere works." The modern form is //go:build expr, it must be above the package clause, and followed by a blank line.
Definition: A constraint is a boolean expression of tags: //go:build linux && (amd64 || arm64), //go:build !debug, //go:build unix. Tags: GOOS, GOARCH, unix, cgo, go1.24 (Go version at least), compiler tags and your own -tags. File names ending _linux.go, _windows_amd64.go and _test.go apply implicit constraints. A file with //go:build ignore is skipped by packages and used for go run gen.go helper scripts.
//go:build debug
package platform
const flavour = "debug"//go:build !debug
package platform
const flavour = "release"package platform
// The _windows suffix is an implicit constraint: only GOOS=windows compiles this file.
const osName = "windows"| Tool | Example | Effect |
|---|---|---|
| Tag expression | //go:build !debug | File compiled unless -tags debug |
| OS suffix | os_windows.go | Only GOOS=windows |
| Arch suffix | hash_arm64.go | Only GOARCH=arm64 |
| Combined suffix | x_linux_arm64.go | Both |
| Version tag | //go:build go1.24 | Compiler at least 1.24 |
| Test-only | integration_test.go with //go:build integration | Runs with go test -tags integration |
| Per-file language | //go:build go1.22 | Also selects that file's language version |
Real scenario: A //go:build integration tag keeps database tests out of go test ./... and into a CI job that starts PostgreSQL. A unix/windows split isolates syscall code. The unix tag exists since Go 1.19, so os_unixlike.go does not list every OS.
Cross-compilation Must-know
In plain words: The Go compiler can build for another operating system or CPU just by setting two environment variables.
Common misunderstanding: "Cross-compiling needs a toolchain per target." Pure Go needs none. Only cgo (C code) needs a cross C compiler, which is why CGO_ENABLED=0 is the usual release setting.
Definition: GOOS and GOARCH select the target; go tool dist list prints the valid pairs. CGO_ENABLED=0 disables cgo so the binary is statically linked and net/os/user fall back to pure Go resolvers.
1 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o dist/hello-linux-amd64 ./cmd/hello
2 CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o dist/hello-linux-arm64 ./cmd/hello
3 CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o dist/hello.exe ./cmd/hello
4 file dist/* -> ELF 64-bit x86-64 statically linked / ELF aarch64 / PE32+ executable| Variable | Typical values | Notes |
|---|---|---|
GOOS | linux, darwin, windows, freebsd, js, wasip1 | js/wasm, wasip1/wasm for WebAssembly |
GOARCH | amd64, arm64, 386, arm, riscv64, wasm | GOARM=7 for 32-bit ARM |
CGO_ENABLED | 0 or 1 | Default 1 when a C compiler exists and not cross-compiling |
GOAMD64 | v1 to v4 | Instruction-set level |
GOARM64 | v8.0 ... | Shown in go version -m |
Real scenario: A laptop on arm64 macOS produces linux/amd64 binaries for a Kubernetes cluster; a FROM scratch image runs the static binary (Containers & Kubernetes).
Stamping and reproducible builds: -ldflags -X, -trimpath Important
In plain words: You can write the release number into the binary at link time, and strip your machine's paths so everyone builds the same bytes.
Common misunderstanding: "-X can set any variable." It sets only package-level string variables that are uninitialised or initialised to a constant string expression (the linker documentation says it will not work if the initialiser makes a function call or refers to other variables), and it needs the full import path: -X academy/toolchain-modules-packages/internal/version.Version=v1.2.3.
Definition: -ldflags passes flags to the linker; -X importpath.name=value sets a string; -s -w drop the symbol table and DWARF (smaller, no debugger); -trimpath rewrites file system paths in the binary to module-relative ones; -buildvcs=false omits version control stamping. A build is reproducible when the same inputs (source, go.sum, Go version, flags, target) give identical bytes.
#!/usr/bin/env bash
# Reproducible, stamped release builds for two binaries and three targets.
set -euo pipefail
MOD=academy/toolchain-modules-packages
VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}
LDFLAGS="-s -w -X ${MOD}/internal/version.Version=${VERSION}"
for target in linux/amd64 linux/arm64 windows/amd64; do
os=${target%/*}
arch=${target#*/}
for cmd in hello worker; do
out="dist/${cmd}-${os}-${arch}"
[ "$os" = windows ] && out="${out}.exe"
# CGO_ENABLED=0 -> static binary and no C cross-compiler needed.
# -trimpath removes local absolute paths so two machines produce the same bytes.
CGO_ENABLED=0 GOOS=$os GOARCH=$arch \
go build -trimpath -ldflags "$LDFLAGS" -o "$out" "./cmd/${cmd}"
done
done
# Record what each binary contains.
go version -m dist/hello-linux-amd64| Flag | Effect | Measured here |
|---|---|---|
| none | Debug info and local paths in the binary | 2,605,186 bytes |
-ldflags='-s -w' | Strip symbols and DWARF | 1,705,570 bytes |
-trimpath | Remove /Users/... from paths | Two copies in different directories get the same SHA-256 |
-X pkg.Var=val | Set string at link time | v1.2.3 printed by -version |
-buildvcs=false | No vcs.* settings | Needed for dirty or non-git trees |
-race | Race detector build | Larger, slower |
Real scenario: Two checkouts of the same source in rA/ and rB/ built without -trimpath produced different hashes (the path appears in the binary six times); with -trimpath they were byte-identical (see Lab).
Build information: ReadBuildInfo and go version -m Important
In plain words: Every Go binary carries a small table saying which Go built it, which module, which dependencies at which versions and, in a git checkout, which commit.
Common misunderstanding: "I need -ldflags for the commit hash." Since Go 1.18 go build stamps vcs.revision, vcs.time and vcs.modified when go build or go install runs inside a Git, Mercurial, Fossil or Bazaar checkout that contains the main package and its module (turn it off with -buildvcs=false), and debug.ReadBuildInfo exposes them.
Definition: runtime/debug.ReadBuildInfo() returns a *BuildInfo with GoVersion, Path, Main module, Deps and Settings (key/value: -ldflags, CGO_ENABLED, GOOS, GOARCH, vcs.revision, vcs.modified). go version -m ./binary prints the same offline.
// Package version reports what was built: values injected with -ldflags -X
// win, and runtime/debug.ReadBuildInfo fills in the rest.
package version
import (
"fmt"
"runtime/debug"
)
// These are strings because the linker's -X flag can only set string
// variables that are not initialised by a function call.
var (
Version = "dev" // go build -ldflags "-X academy/toolchain-modules-packages/internal/version.Version=v1.2.3"
Commit = "unknown" // normally filled from the vcs.revision build setting
)
// Info is the build identity of the running binary.
type Info struct {
Version string
Commit string
Modified bool
GoVersion string
Module string
}
// Read combines the linker-injected values with the embedded build info.
func Read() Info {
info := Info{Version: Version, Commit: Commit}
bi, ok := debug.ReadBuildInfo()
if !ok {
return info // binary built without module support
}
info.GoVersion = bi.GoVersion
info.Module = bi.Main.Path
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
if info.Commit == "unknown" {
info.Commit = s.Value
}
case "vcs.modified":
info.Modified = s.Value == "true"
}
}
return info
}
// String renders the identity on one line, as `--version` flags do.
func (i Info) String() string {
dirty := ""
if i.Modified {
dirty = "+dirty"
}
return fmt.Sprintf("%s (%s%s, %s, module %s)", i.Version, i.Commit, dirty, i.GoVersion, i.Module)
}package version
import (
"strings"
"testing"
)
func TestReadDefaults(t *testing.T) {
info := Read()
if info.Version != "dev" {
t.Fatalf("Version = %q, want dev (no -X flag in plain go test)", info.Version)
}
if !strings.HasPrefix(info.GoVersion, "go1.") {
t.Fatalf("GoVersion = %q, want a go1.x string", info.GoVersion)
}
}
func TestStringMarksDirtyTrees(t *testing.T) {
got := Info{Version: "v1", Commit: "abc", Modified: true, GoVersion: "go1.24", Module: "m"}.String()
want := "v1 (abc+dirty, go1.24, module m)"
if got != want {
t.Fatalf("String() = %q, want %q", got, want)
}
}Real scenario: A /version endpoint and a startup log line print Info.String(); vulnerability scanners (govulncheck) read the same table to find which dependency versions are inside a deployed binary. The fleet table below is filled from it.
-- Which running instances were built from a dirty tree or an old Go release?
SELECT service, instance_id, version, go_version
FROM deployed_builds
WHERE vcs_modified OR go_version < 'go1.24'
ORDER BY service, started_at;The table that query reads, filled at startup from Info:
-- A table an operations service could fill from `go version -m` / ReadBuildInfo
-- at startup, so "which build is running where" is a query, not a guess.
CREATE TABLE deployed_builds (
service text NOT NULL,
instance_id text NOT NULL,
version text NOT NULL, -- -X ...Version=v1.2.3
vcs_revision text NOT NULL, -- vcs.revision build setting
vcs_modified boolean NOT NULL DEFAULT false,
go_version text NOT NULL, -- runtime/debug BuildInfo.GoVersion
module_sums jsonb NOT NULL DEFAULT '{}', -- path -> h1: hash from BuildInfo.Deps
started_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (service, instance_id)
);
-- Which running instances were built from a dirty tree or an old Go release?
SELECT service, instance_id, version, go_version
FROM deployed_builds
WHERE vcs_modified OR go_version < 'go1.24'
ORDER BY service, started_at;The environment and the module cache: go env, GOMODCACHE Good to know
In plain words: go env prints how the tool is configured; downloaded modules live in a read-only cache you can wipe at any time.
Common misunderstanding: "GOPATH still holds my source." It holds bin/ (installed tools) and pkg/mod (the module cache); your code lives anywhere.
Definition:
| Variable | Typical value | Purpose |
|---|---|---|
GOROOT | /opt/homebrew/Cellar/go/1.27.4/libexec | The installed toolchain |
GOPATH | ~/go | Parent of bin/ and pkg/mod |
GOBIN | empty | Where go install writes; defaults to $GOPATH/bin |
GOMODCACHE | ~/go/pkg/mod | Unpacked module versions; files are read-only (use -modcacherw to change) |
GOCACHE | OS cache dir | Compiled package and test cache |
GOENV | ~/Library/Application Support/go/env | The file go env -w writes |
GOWORK | empty or a path | Active go.work |
GOFLAGS, GOPROXY, GOSUMDB, GOPRIVATE, GOTOOLCHAIN | see above | Behaviour |
GOOS, GOARCH, CGO_ENABLED | host values | Build target |
go clean -modcache deletes the module cache (it is rebuilt from the proxy); go clean -cache drops compiled output; go clean -testcache forgets cached test results.
Mechanics
Error texts decoded Must-know
Every text below was produced by the lab commands, except the two marked from documentation.
| Message | Meaning | Fix |
|---|---|---|
no required module provides package golang.org/x/text/language; to add it: go get golang.org/x/text/language | Import has no require in go.mod | go get or go mod tidy |
missing go.sum entry for module providing package golang.org/x/text/language (imported by example.com/demo); to add: go get example.com/demo | go.sum incomplete | go mod tidy; commit go.sum |
package example.com/cyc/a imports example.com/cyc/b from a.go imports example.com/cyc/a from b.go: import cycle not allowed | Two packages import each other | Extract shared types, or invert with an interface |
use of internal package example.com/lib/internal/secret not allowed | Importer is outside the parent tree | Move code, or expose a public package |
undefined: strings.toLower (but have ToLower) | Lowercase name from another package | Use the exported name |
package example.com/nm is not a main package | go run of a library | Run a package main directory |
go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local) | Toolchain too old and switching off | Install it or allow auto |
go: download go1.99.0 for darwin/arm64: toolchain not available | No such toolchain exists | Fix the go line |
module example.com/lib provides package example.com/lib/internal/secret and is replaced but not required; to add it: go get example.com/lib | replace without require | Add the require line |
go: updates to go.mod needed; to update it: go mod tidy | Read-only mode needs an edit | Run go mod tidy |
go: -mod may only be set to readonly or vendor when in workspace mode | -mod=mod inside a workspace | GOWORK=off or drop the flag |
SECURITY ERROR ... checksum mismatch (documentation) | Downloaded bytes differ from go.sum or the checksum database | Do not bypass; investigate |
go: errors parsing go.mod (documentation) | Syntax error in go.mod | Fix the line shown |
Reading the module graph Good to know
$ go mod graph
example.com/app example.com/lib@v0.0.0
example.com/app go@1.27.4
example.com/app golang.org/x/text@v0.44.0
golang.org/x/text@v0.44.0 golang.org/x/tools@v0.52.0
$ go mod why golang.org/x/text/language
# golang.org/x/text/language
example.com/app
golang.org/x/text/language| Tool | Answers | Output shape |
|---|---|---|
go list -m all | Which versions are in the build? | path version per line |
go list -m -u all | Which have newer versions? | Adds [v1.5.0] |
go list -m -versions x | Which versions exist? | One line |
go list -deps ./cmd/hello | Which packages are compiled? | Import paths |
go list -f '{{.ImportPath}} {{.Name}}' ./... | Package names per directory | Template |
go mod graph | Who requires whom? | from to edges |
go mod why -m x | Why is x needed? | Chain |
Static versus cgo, and what a go build embeds Good to know
| Property | CGO_ENABLED=1 | CGO_ENABLED=0 |
|---|---|---|
| Binary links libc dynamically (Linux) | Often, for net and os/user | No: fully static |
Needs gcc or clang | Yes | No |
Cross-compile with GOOS/GOARCH only | No (needs a cross C compiler) | Yes |
| DNS resolver | cgo resolver by default on some OSes | Pure Go resolver |
SQLite via mattn/go-sqlite3 | Works | Fails; use a pure Go driver |
Image FROM scratch | Needs libc | Works |
Solving the classic problems
| Problem | Solution | How | Cost |
|---|---|---|---|
| New dependency in code | Tidy | go mod tidy then commit both files | A network fetch |
| Edit a dependency while testing | Workspace | go work init . ../lib | Do not commit go.work |
| Fix a dependency now, upstream later | Replace to a fork | replace x => github.com/you/x v1.2.3-fix | Maintain the fork |
| Private repositories | Mark private | GOPRIVATE=git.corp/* and git credentials | Lose proxy cache for them |
| Offline or locked-down CI | Vendor | go mod vendor, -mod=vendor, commit vendor/ | Big diffs |
Version in --version | Stamp | -ldflags "-X pkg.Version=$VERSION" | Build script |
| Same bytes everywhere | Reproducible build | -trimpath, CGO_ENABLED=0, pinned toolchain, no -buildvcs surprises | Discipline |
| Build for another platform | Cross-compile | GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build | cgo is off |
| Two binaries, shared code | cmd/ plus internal/ | One module, many mains | Shared release cadence |
| Break a package cycle | Interface at the boundary | Define the interface where it is used | One more type |
Break an import cycle Important
In plain words: If orders needs billing and billing needs orders, the compiler stops; the fix is a third place for what they share, or an interface owned by the consumer.
Common misunderstanding: "Import cycles are a Go limitation to work around with build tags." They are a design signal; the dependency direction was never settled.
Definition: The import graph of a program must be acyclic, because package initialisation order is defined by it.
1 orders imports billing (orders.Charge calls billing.Create)
2 billing imports orders (billing.Create takes an orders.Order) -> cycle
3 move Order into package model; both import model -> fixed
4 or: billing defines type Order interface { Total() int }; orders passes its own typeReal scenario: A user package that wants session, which wants user; extracting identity (IDs and a small struct) removes the loop.
Make a stamped release in one command Good to know
1 VERSION=v1.2.3 ./ref/build.sh
2 go version -m dist/hello-linux-amd64 -> build -ldflags="-s -w -X .../version.Version=v1.2.3"
3 ./dist/hello-linux-amd64 -version -> v1.2.3 (<revision>, go1.24.3, module academy/...)Compare with the Dockerfile and Makefile targets in Project Layout, which call exactly these commands.
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Single service | One module, cmd/<name>, internal/ | go 1.24 plus a toolchain line | Least ceremony |
| Several services owned by one team | One module, many cmd/ | internal/ for shared code | One version, atomic changes |
| Library you publish | One module at repo root | Semantic versions, retract on mistakes | Consumers get MVS |
| Two repos changing together | Workspace | GOWORK=off in CI | No replace commits |
| Strict supply chain | Vendor plus GOFLAGS=-mod=vendor | go mod verify, GOFLAGS=-mod=readonly | Offline and reviewable |
| Many teams and a mono-repo | One module per team boundary | Workspaces locally | Independent versions |
| Release binaries | CGO_ENABLED=0, -trimpath, -ldflags | Pin GOTOOLCHAIN | Same bytes, small image |
| Tool needed by developers | tool directive and go tool | go get -tool | Pinned versions without tools.go |
| Need a C library | CGO_ENABLED=1 in a matching build image | Build per target natively | Cross C compilers are costly |
For PHP/Laravel developers
Composer resolves the newest version that satisfies composer.json constraints and records it in composer.lock; Go resolves the minimum that satisfies every require and needs no lock file. vendor/ in PHP is mandatory and untracked; in Go it is optional and, if used, committed.
| PHP / Composer | Go |
|---|---|
composer.json require | go.mod require |
composer.lock | go.sum verifies; the build list is derived |
composer update | go get -u ./... |
composer install | go build (downloads on demand) |
autoload PSR-4 namespaces | Import path = directory path |
private/protected/public | Capital letter; internal/ |
config/app.php bootstrapping, service providers boot() | Explicit constructors from main; avoid init() |
php artisan commands | cmd/<name> binaries |
// Composer: any compatible 1.x, resolved to the newest at update time
"require": { "monolog/monolog": "^3.5" }
// Go: a minimum, resolved by MVS, the same on every machine
// require github.com/rs/zerolog v1.33.0Go
Example
The module under docs/snippets/go/toolchain-modules-packages/go has two binaries (cmd/hello, cmd/worker), five internal packages, build-tagged files and tests. It compiles and passes go vet and go test; every snippet above is a file from it.
The Go angle
Everything about the toolchain is in the standard distribution: formatting (gofmt), static checks (go vet), tests, race detector, documentation (go doc), dependency management, cross-compilation. The language adds only one visibility rule and one initialisation rule; the rest is conventions the go command enforces (internal/, _test.go, testdata). What the tool does not give you is a lock file, a plugin system for the build, or implicit imports.
In architecture: from a single process to a distributed system
Monolith: one process, one database
One module, one cmd/server, packages by feature under internal/. go build gives one static binary. The toolchain line makes every laptop and the CI builder identical. Version stamping (-X) means a bug report quotes v1.2.3 (abc1234).
Modular monolith and multiple databases
Boundaries become packages with explicit exported APIs; internal/orders exposes orders.Service, and its repository types stay lowercase. A compile-time cycle between orders and billing is the cheapest architectural alarm you will ever get. Multiple databases appear as separate packages that own their connection (see database/sql & pgx).
Microservices
Each service is a module or a cmd/ directory. Shared contracts (protobuf-generated code, event schemas) become a small module versioned with /v2 when they break; consumers upgrade at their own pace, and MVS means the highest requirement in the graph wins, so a service that imports two shared modules never gets a surprise upgrade. GOPRIVATE and an internal proxy are the infrastructure. See Event-Driven Go for the contracts that cross the wire.
Distributed data: replicas, caches, NAT and containers
Reproducible binaries make rollbacks meaningful: the image digest, the module sums and the stamped revision identify the same bytes on every node. The deployed_builds table above lets operations query "which replicas run a dirty or old-Go build". Containers want static binaries (CGO_ENABLED=0) and -trimpath; Kubernetes rollouts that mix versions need /v2 discipline for message schemas (Containers & Kubernetes).
Scaling path: 1×, 10×, 100×
| Scale | Toolchain and modules | What changes |
|---|---|---|
| 1× (one developer) | go run, no proxy config | Nothing to manage |
| 10× (a team) | toolchain line, go.sum committed, CI go vet, go test -race | Pinning and gates |
| 100× (many teams) | Internal proxy, GOPRIVATE, GOFLAGS=-mod=readonly, vendoring or module mirror, govulncheck on ReadBuildInfo | Supply-chain controls and build caching |
Lab
The module is docs/snippets/go/toolchain-modules-packages/go. Copy it to a scratch directory so binaries do not land in the repository. Outputs below were produced on the author's machine (Go 1.27.4, macOS arm64) and are real, except the toolchain download, which is expected, not run (the sandbox's proxy returned 403 for toolchain zips).
$ cp -r docs/snippets/go/toolchain-modules-packages/go /tmp/lab && cd /tmp/lab && mkdir bin
$ go run ./cmd/hello -name Ada
Hello, Ada!
platform: release on unix-like
plugins: [alpha beta]
$ go run -tags debug ./cmd/hello
Hello, world!
platform: debug on unix-like
plugins: [alpha beta]
$ go run ./cmd/hello -version
dev (unknown, go1.27.4, module academy/toolchain-modules-packages)
$ go build -ldflags "-X academy/toolchain-modules-packages/internal/version.Version=v1.2.3 -X academy/toolchain-modules-packages/internal/version.Commit=abc1234" -o bin/hello ./cmd/hello && ./bin/hello -version
v1.2.3 (abc1234, go1.27.4, module academy/toolchain-modules-packages)
$ go version -m bin/hello
bin/hello: go1.27.4
path academy/toolchain-modules-packages/cmd/hello
mod academy/toolchain-modules-packages (devel)
build -buildmode=exe
build -compiler=gc
build -ldflags="-X academy/toolchain-modules-packages/internal/version.Version=v1.2.3 -X academy/toolchain-modules-packages/internal/version.Commit=abc1234"
build CGO_ENABLED=1
build GOARCH=arm64
build GOOS=darwinStamp and inspect, as above. Expected:
-versionprints the injected values.Cross-compile three targets and look at them:
$ for t in linux/amd64 linux/arm64 windows/amd64; do GOOS=${t%/*} GOARCH=${t#*/} CGO_ENABLED=0 go build -o bin/hello-${t%/*}-${t#*/} ./cmd/hello; done
$ file bin/hello-*
bin/hello-linux-amd64: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, Go BuildID=...
bin/hello-linux-arm64: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, Go BuildID=...
bin/hello-windows-amd64: PE32+ executable (console) x86-64, for MS Windows
$ go build -o bin/h1 ./cmd/hello; go build -ldflags='-s -w' -o bin/h2 ./cmd/hello; ls -l bin/h1 bin/h2 | awk '{print $5, $9}'
2605186 bin/h1
1705570 bin/h2- Reproducibility: build the same source in two directories, with and without
-trimpath:
$ for d in rA rB; do (cd $d && go build -o out-plain ./cmd/hello && go build -trimpath -o out-trim ./cmd/hello); done
$ shasum -a 256 rA/out-plain rB/out-plain rA/out-trim rB/out-trim | cut -c1-16,65-
c68f1deb15359cb0 rA/out-plain
a3952578126a4653 rB/out-plain <- different: the absolute path is inside
cf4b6becfd62fd2d rA/out-trim
cf4b6becfd62fd2d rB/out-trim <- identical
$ strings rA/out-plain | grep -c rA ; strings rA/out-trim | grep -c rA
6
0- Fail on purpose: dependency, missing sum, unknown module.
$ mkdir demo && cd demo && go mod init example.com/demo
go: creating new go.mod: module example.com/demo
$ go build ./... # main.go imports golang.org/x/text/language
main.go:6:2: no required module provides package golang.org/x/text/language; to add it:
go get golang.org/x/text/language
$ go mod tidy
go: finding module for package golang.org/x/text/language
go: found golang.org/x/text/language in golang.org/x/text v0.44.0
$ cat go.sum
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
$ rm go.sum && go build ./...
main.go:6:2: missing go.sum entry for module providing package golang.org/x/text/language (imported by example.com/demo); to add:
go get example.com/demo- Cycle and
internal/:
$ go build ./... # a imports b, b imports a
package example.com/cyc/a
imports example.com/cyc/b from a.go
imports example.com/cyc/a from b.go: import cycle not allowed
$ go build . # in module app, importing example.com/lib/internal/secret
package example.com/app
main.go:2:8: use of internal package example.com/lib/internal/secret not allowed- Toolchain too old (expected from a real run) and switching (expected, not run for the download):
$ printf 'module example.com/tc\n\ngo 1.99\n' > go.mod && GOTOOLCHAIN=local go build .
go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local)
$ printf 'module example.com/tc\n\ngo 1.24.0\n' > go.mod && go version # expected, not run on a machine with Go < 1.24
go: downloading go1.24.0 (darwin/arm64)
go version go1.24.0 darwin/arm64- Workspace and replace:
$ go work init ./app ./lib && cat go.work
go 1.27.4
use (
./app
./lib
)
$ cd app && go run . # imports example.com/lib with no require and no replace
hi
$ GOWORK=off go run .
main.go:2:15: no required module provides package example.com/lib; to add it:
go get example.com/lib- Vendor:
go mod vendorwrotevendor/modules.txtlisting# golang.org/x/text v0.44.0,## explicit; go 1.26.0and the four packages used;go build -mod=vendor .succeeded.
Run the module's own tests (all pass; the platform test runs in both flavours):
$ go vet ./... && go test ./... && go test -tags debug ./internal/platform/ && go test -race ./...Common misconceptions
| Belief | Reality |
|---|---|
go.sum is a lock file | The build list comes from go.mod through MVS; go.sum only verifies bytes |
| Go always picks the newest dependency | It picks the highest version required by anyone; newer releases are ignored until requested |
go 1.24 is the toolchain that builds | It is a minimum and the language version; toolchain and GOTOOLCHAIN decide the compiler |
go build fetches missing imports | Not since Go 1.16; run go get or go mod tidy |
replace in my library fixes my users' builds | Only the main module's replace counts |
A tag v2.0.0 is enough for a major version | The module path needs /v2 and every import must include it |
init() is a safe place for setup | It cannot fail cleanly, runs in every test binary and hides order dependencies |
| Cross-compiling needs special compilers | Pure Go needs only GOOS/GOARCH; only cgo needs a C cross-compiler |
internal/ is a convention | The go command rejects the import with an error |
| The package name must equal the directory name | Only the package clause counts; it conventionally matches |
go run leaves a binary | It builds into a temp directory and deletes it |
| Workspaces make the published build different | go.work is local; CI should build with GOWORK=off |
Cheat sheet
| Topic | What to remember |
|---|---|
| New project | go mod init example.com/app, then go mod tidy after imports change |
| Daily loop | go run, go test ./..., go vet ./..., gofmt -l . |
| Release build | CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X pkg.Version=$V" ./cmd/x |
| Toolchain | go line = minimum; toolchain = suggestion; GOTOOLCHAIN = policy |
| Dependencies | go get pkg@v1.2.3, go get -u ./..., go mod tidy, commit go.mod and go.sum |
| Why is it here | go mod why -m x, go mod graph, go list -m all |
| Local development | go work init; never commit a replace => ../x |
| Private modules | GOPRIVATE=git.corp/* plus git credentials |
| Major versions | /v2 in module and in imports; +incompatible otherwise |
| Visibility | Capital letter = package export; internal/ = module-tree export |
init() | Registration only; blank import for drivers |
| Multi-binary | cmd/<name>/main.go; share code under internal/ |
| Build tags | //go:build tag above package; _linux.go suffixes |
| Build info | debug.ReadBuildInfo(), go version -m binary |
| Errors | missing go.sum entry -> tidy; import cycle -> interface or extract; internal -> move |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does the go line in go.mod mean since Go 1.21, and how does it differ from toolchain? Important
Answer
Answer: The go line is the minimum Go version and the language version for the module; the toolchain line is only a suggested toolchain. If the installed go is older than the requirement, GOTOOLCHAIN=auto downloads a newer one; local refuses with go.mod requires go >= X.
2 — Why does Go not need a lock file? Must-know
Answer
Answer: Minimal version selection is deterministic: it takes the highest version required anywhere in the module graph, and new releases change nothing until a requirement is raised. go.sum only verifies hashes.
3 — Which commands fix no required module provides package ... and missing go.sum entry ...? Must-know
Answer
Answer: Both are fixed by go mod tidy (or go get MODULE); commit go.mod and go.sum. Read-only mode is the default since Go 1.16, so go build never edits them.
4 — A library tags v2.0.0. What must change in the repository so users can go get it? Important
Answer
Answer: The module line must end in /v2 (on the major branch or in a v2/ subdirectory with its own go.mod) and every internal and external import must use the /v2 path.
5 — What do GOPRIVATE, GONOPROXY and GONOSUMDB do? Important
Answer
Answer: GOPRIVATE is a list of path prefixes treated as private; it is the default for both others. GONOPROXY makes the go command fetch them directly instead of through the proxy; GONOSUMDB skips the checksum database lookup for them.
6 — In which order do package variables, init() functions and main run? Must-know
Answer
Answer: Imported packages first (each once), then the package's variables in dependency order, then its init() functions in file presentation order, then main.main.
7 — What is the difference between a capital letter and internal/? Must-know
Answer
Answer: A capital letter exports an identifier from its package to every importer; internal/ limits which packages (those rooted at the parent of internal) may import a package at all, enforced by the go command.
8 — How do you embed the version into a binary, and why must you give the full import path? Good to know
Answer
Answer: -ldflags "-X full/import/path/pkg.Version=v1.2.3"; the linker identifies the variable by import path plus name, and only package-level string variables can be set.
9 — What two things make a Go build reproducible across directories and machines? Important
Answer
Answer: -trimpath (no absolute paths in the binary) and identical inputs: source, go.sum, Go version, flags and target (use CGO_ENABLED=0 to avoid C toolchain differences).
10 — When should you use a workspace instead of replace? Important
Answer
Answer: When developing several local modules at once: a workspace is not committed and leaves go.mod clean, while a committed replace with a local path breaks everyone else's build.
11 — Why is init() discouraged for application code? Important
Answer
Answer: It cannot return errors, runs in every importer including tests, hides dependencies behind blank imports and makes order matter; prefer explicit construction in main.
Glossary
| Term | Meaning |
|---|---|
| Module | A tree of packages released together, rooted at a directory with go.mod |
| Module path | The name in the module line; prefix of every import path in the module |
| Package | A directory of .go files sharing a package clause; unit of compilation and visibility |
| Import path | Module path plus relative directory, as written in import |
go directive | Minimum Go version and language version for the module |
toolchain directive | Suggested toolchain; a floor, not a ceiling |
GOTOOLCHAIN | Policy for choosing or downloading the toolchain: auto, local, path, or a version |
require | Minimum version of a dependency |
replace | Substitute a module or version with another module or directory (main module only) |
exclude | Forbid a specific module version |
retract | The publisher's declaration that versions must not be used |
go.sum | File of cryptographic hashes verifying downloaded modules |
| Checksum database | sum.golang.org, the public transparent log of module hashes (GOSUMDB) |
GOPROXY | Ordered list of module proxies; direct means version control |
GOPRIVATE | Prefixes treated as private; implies GONOPROXY and GONOSUMDB |
GONOSUMDB | Prefixes excluded from checksum database lookups |
GOFLAGS | Default flags for every go command |
| Minimal version selection | Algorithm that selects the highest version required in the graph |
| Build list | The module versions MVS chooses; printed by go list -m all |
| Semantic import versioning | Major versions 2+ add /vN to the module and import paths |
| Pseudo-version | Version for an untagged commit: base, UTC timestamp, 12-char hash |
+incompatible | Suffix for v2+ tags in a repository without go.mod |
Workspace / go.work | A set of local modules treated as main modules together |
| Exported identifier | A name starting with an upper-case letter, visible to other packages |
| Internal package | A package under an internal/ directory, importable only from the parent tree |
init() | A function run automatically during package initialisation; cannot be called |
| Blank import | import _ "path"; imports only for init() side effects |
cmd/ | Conventional directory holding one package main per binary |
Build tag / //go:build | A constraint that includes or excludes a file from a build |
GOOS, GOARCH | Target operating system and CPU architecture |
CGO_ENABLED | Whether C code may be linked; 0 gives static, cross-compilable binaries |
-ldflags -X | Linker flag that sets a package-level string variable |
-trimpath | Compiler flag that removes file system paths from the binary |
| Reproducible build | Same inputs produce byte-identical binaries |
ReadBuildInfo | runtime/debug function returning embedded build metadata |
Module cache / GOMODCACHE | Directory with downloaded, read-only module versions |
| Vendor directory | Optional copy of dependencies inside the module (vendor/) |
| Import cycle | Two packages importing each other, forbidden by the compiler |
References
- Go Modules Reference — https://go.dev/ref/mod (fetched; MVS, pseudo-versions, checksum database,
GOVCS, workspaces) - Go Toolchains — https://go.dev/doc/toolchain (fetched;
goandtoolchainlines,GOTOOLCHAIN) - go.mod file reference — https://go.dev/doc/modules/gomod-ref
- Managing dependencies — https://go.dev/doc/modules/managing-dependencies
- Using Go Modules — https://go.dev/blog/using-go-modules
- Go Modules: v2 and Beyond — https://go.dev/blog/v2-go-modules
- Module version numbering — https://go.dev/doc/modules/version-numbers
- Organizing a Go module — https://go.dev/doc/modules/layout
- Getting started with multi-module workspaces — https://go.dev/doc/tutorial/workspaces
- Module Mirror and Checksum Database Launched — https://go.dev/blog/module-mirror-launch
- Checksum database — https://sum.golang.org/
- Perfectly Reproducible, Verified Go Toolchains — https://go.dev/blog/rebuild
- The Go Programming Language Specification (Package initialization, Program execution, Exported identifiers) — https://go.dev/ref/spec
- Effective Go — https://go.dev/doc/effective_go
- Go FAQ — https://go.dev/doc/faq
- Go Code Review Comments — https://go.dev/wiki/CodeReviewComments
- Installing Go from source (GOROOT, GOPATH, GOBIN) — https://go.dev/doc/install/source
- Go 1.18 release notes — https://go.dev/doc/go1.18
- Go 1.19 release notes — https://go.dev/doc/go1.19
- Go 1.21 release notes — https://go.dev/doc/go1.21
- Go 1.22 release notes — https://go.dev/doc/go1.22
- Go 1.23 release notes — https://go.dev/doc/go1.23
- Go 1.24 release notes — https://go.dev/doc/go1.24
- Go 1.25 release notes — https://go.dev/doc/go1.25
- Vulnerability management for Go — https://go.dev/security/vulncheck