Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why modules, why a toolchain lineWhy it exists
GOPATH, vgo, Go 1.11 to 1.21Where it comes from
Which Go version runs, GOTOOLCHAINInstalling and choosing a toolchain
go run, build, install, test, vet, fmt, doc, generateThe go command
module, go, toolchain, require, replace, exclude, retractgo.mod
missing go.sum entry, checksum databasego.sum and the checksum database
GOPROXY, GOPRIVATE, GONOSUMDB, GOFLAGSProxies and private modules
v2, v0.0.0-2025...-abcdef123456, +incompatibleVersions
Which version does Go pickMinimal version selection
go get, go mod tidy, vendor, why, graphManaging dependencies
Working on two modules at onceWorkspaces
Directory versus package versus modulePackages
Capital letters, internal/Exported identifiers and internal packages
init(), blank importsinit and package initialisation
package main, cmd/main and multiple binaries
//go:build, _linux.goBuild tags
GOOS, GOARCH, CGO_ENABLEDCross-compilation
-ldflags -X, -trimpath, reproducibilityStamping and reproducible builds
ReadBuildInfo, go version -mBuild information
go env, GOMODCACHEThe environment and the module cache
Exact error textsError texts decoded
Fixes for common situationsSolving the classic problems
Composer and Laravel comparisonFor PHP/Laravel developers
From one binary to many servicesIn architecture
Commands with real outputLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The four nested units. Each row is unpacked in the concept catalogue.

UnitIn plain wordsWhere it livesNamed by
ModuleA versioned bundle of packagesA directory tree with go.mod at its rootThe module line, for example github.com/acme/shop
PackageThe unit of compilation and of visibilityOne directory, one package nameImport path = module path + relative directory
FileA source file with a package clause.go files in that directoryFile name; suffixes _linux, _test mean something
IdentifierA function, type, variable, constant, field or method nameInside a fileA capital first letter exports it

The files you will meet.

FileWho writes itWhat it holdsCommit it?
go.modYou and the go commandModule path, Go version, requirements, replacementsYes
go.sumThe go commandCryptographic hashes of every module version usedYes
go.workYou, for local developmentWhich local modules form one workspaceUsually no
go.work.sumThe go commandHashes needed only in workspace modeSame as go.work
vendor/ and vendor/modules.txtgo mod vendorA copy of the dependenciesOnly if you vendor
$GOROOT/go.envThe Go distributionDefault GOPROXY, GOSUMDB, GOTOOLCHAINNo
go env file (os.UserConfigDir()/go/env)go env -wYour per-user defaultsNo

The commands.

CommandWhat it doesWrites a binary?Typical use
go run ./cmd/apiCompile to a temp directory and executeNo (temp)Development loop
go build ./...Compile; discard results for libraries, keep the binary for one main with -oWith -o or one main in cwdCI compile check, release builds
go install ./cmd/apiCompile and place in $GOBIN (default $GOPATH/bin)Yes, installedTools for your machine
go test ./...Compile test binaries and run themNoTests
go vet ./...Static checks for suspicious codeNoCI gate
gofmt -l . / go fmt ./...List or rewrite non-canonical formattingNoCI gate, editor save
go mod tidyAdd missing, drop unused requirements, fix go.sumNoAfter every import change
go get pkg@v1.2.3Add, upgrade or downgrade one requirementNoDependency changes
go work init ./a ./bCreate a workspaceNoMulti-module development
go env GOPROXYPrint configurationNoDebugging
go doc fmt.PrintlnPrint documentation from sourceNoOffline reference
go generate ./...Run //go:generate commandsNoCodegen 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.

QuestionAnswered byWhat you pay
Which code is "mine"?The module line and the directory tree under go.modA module path you can never casually change
Which versions do I need?require plus minimal version selectionUpgrades are explicit; nothing moves by itself
Is the code I downloaded the code everyone else got?go.sum plus the checksum databaseAn extra network call the first time
Which compiler builds it?The go and toolchain lines plus GOTOOLCHAINA 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 package clause; a module is a tree of packages with one go.mod.
  • "go.sum is the lock file". It is not. The build list is recomputed from go.mod by minimal version selection every time; go.sum only proves that the bytes match.
  • "go 1.24 in go.mod is 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 / versionWhat changedWhy it matters now
Go 1.0 to 1.10go get clones into $GOPATH/src; no versionsOld tutorials still say "put it in GOPATH"
2018Russ 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/srcgo.mod and go.sum appear
Go 1.13 (2019)Module mode is the default; module mirror and checksum database are defaultGOPROXY and GOSUMDB defaults
Go 1.16 (2021)-mod=readonly is the default: builds never edit go.modYou must run go mod tidy or go get yourself
Go 1.18 (2022)Workspaces (go.work); binaries embed version-control informationMulti-module development, vcs.revision
Go 1.19 (2022)The unix build constraintOne tag for all Unix-like systems
Go 1.21 (2023)go line is a strict minimum; toolchain line; automatic toolchain downloadGOTOOLCHAIN exists
Go 1.24 (2025)tool directive and go get -tool; go tool runs module-pinned toolsReplaces the tools.go blank-import trick
Go 1.25 (2025)ignore directive in go.modDirectories 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/amd64

Real 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.

go.modgo 1.24.0toolchain go1.24.3GOTOOLCHAINauto = local+autobundled go older?compare versionsrun bundled golocal is new enoughdownload + rungolang.org/toolchainnoyesGOTOOLCHAIN=local never switches; =path never downloads; =go1.24.3+auto pins a floor.
GOTOOLCHAIN valueBehaviourUse it when
auto (default in standard distributions)Same as local+auto: use the bundled toolchain unless go.mod needs newer, then downloadDeveloper laptops
localAlways the bundled toolchain; refuse modules that need newerHermetic or air-gapped builds
go1.24.3Always that toolchainReproducing a bug on an exact version
go1.24.3+autoAt least 1.24.3; switch further if go.mod says soA team-wide floor
path / local+pathLook for a goX.Y.Z binary on PATH; never downloadPre-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 code

Real 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.

VerbFlags worth knowingWhat it will not do
go run-race, -tags x, arguments after the packageKeep the binary
go build-o, -trimpath, -ldflags, -tags, -race, -buildvcs=false, -v, -xInstall anything
go installpkg@version (outside any module)Edit go.mod when given @version
go test-run, -v, -count=1, -race, -cover, -short, -tagsRun //go:build ignore files
go vet-printf=false and per-analyser switchesFind races or logic bugs
go fmt / gofmtgofmt -l, -d, -w, -sReorder imports across groups beyond sorting
go docgo doc pkg.Symbol, -all, -srcFetch network docs
go generate-run regexp, -nRun automatically during build
go list-m all, -deps, -f template, -jsonChange files
go clean-cache, -modcache, -testcacheTouch 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:

DirectiveMeaningWho may use it
moduleThe module path (with /v2 suffix from major 2 on)Every module
goMinimum Go version and language versionEvery module
toolchainSuggested toolchain, only a floorOptional
godebugSets GODEBUG defaults (default=go1.24, panicnil=1)Main module (Go 1.23+)
requireMinimum version of a dependency; // indirect marks ones you do not import directlyEvery module
replaceSwap a module (or one version) for another module or a local directoryMain module only
excludeForbid one exact versionMain module only
retractSay that versions you published must not be usedThe publisher, in the newer version
toolPin an executable dependency for go tool (Go 1.24+)Main module
ignoreDirectories 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.

txt
// 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.

SituationWhat go doesCommand to fix
Hash missingmissing go.sum entry for module providing package ...go mod tidy or go get <module>
Hash differentverifying module: checksum mismatchInvestigate; never just delete the line
Private moduleSkip the checksum database via GOPRIVATE / GONOSUMDBSet the variable
OfflineGOFLAGS=-mod=mod cannot help; use vendor/ or a proxygo mod vendor
Old linesHarmlessgo 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:

VariableDefaultMeaning
GOPROXYhttps://proxy.golang.org,directComma- or pipe-separated list of proxies; direct means VCS; off forbids network
GOSUMDBsum.golang.orgChecksum database; off disables verification
GOPRIVATEemptyGlob list of module path prefixes that are private: implies GONOPROXY and GONOSUMDB
GONOPROXYGOPRIVATEPaths fetched directly, never via a proxy
GONOSUMDBGOPRIVATEPaths not looked up in the checksum database
GOINSECUREemptyPaths allowed over plain HTTP or unverified TLS
GOVCSpublic:git|hg,private:allWhich version-control tools may be used for which hosts
GOFLAGSemptyDefault flags for every go command, -mod=vendor, -modcacherw
GOMODCACHE$GOPATH/pkg/modWhere 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=1
go buildneeds x v1.4.0Module cacheGOMODCACHEGOPROXYproxy.golang.orgdirect (VCS)git, hg ... per GOVCSgo.sumlocal hashessum.golang.orgGOSUMDBmissGOPRIVATE / GONOPROXY skip the proxy; GOPRIVATE / GONOSUMDB skip the checksum databasehit: done

Real 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:

FormExampleMeaning
Releasev1.4.2A tagged commit
Pre-releasev1.5.0-rc.1Sorted before v1.5.0
Pseudo-versionv0.0.0-20191109021931-daa7c04131f5An untagged commit: base + UTC commit time + 12-character hash
Pseudo after a tagv1.2.4-0.20191109021931-daa7c04131f5Untagged commit after v1.2.3
+incompatiblev2.1.0+incompatibleA v2+ tag in a repository without go.mod
Queries@latest, @v1, @none, @master, @abc1234Accepted by go get; resolved to one of the above
v0.x.yv0.3.1No compatibility promise
module github.com/acme/lib/v2        // in the v2 go.mod

import "github.com/acme/lib/v2/store" // every importer writes /v2

Two 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".

main modulego.modA v1.2B v1.2C v1.3C v1.4D v1.2require A >= 1.2, B >= 1.2Build list: A 1.2, B 1.2, C 1.4 (highest required), D 1.2. Newer releases exist but nothing asks for them.
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 it

Real 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
CommandEffectNotes
go get pkg@v1.2.3Set 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 pkgAdd a tool directive (Go 1.24)Run with go tool name
go mod tidyAdd missing and remove unused requirements and sumsConsiders tests of the main module's packages
go mod downloadFill the module cache; -x shows the commandsWarm CI caches
go mod verifyRe-hash the module cache against go.sumDetects local tampering
go mod vendorCopy needed packages to vendor/ and write vendor/modules.txtThen -mod=vendor is automatic when go 1.14+
go mod why -m xShortest import chain from your main module to xAnswers "why is this here?"
go mod graphPrint module requirements, one edge per lineFeed to grep, dot
go list -m allPrint the build listAfter MVS
go mod editScriptable edits and -json outputFor 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.

DirectiveScopeLifetimeBest for
replace => ../localMain module onlyWhile debuggingEditing a dependency alongside
replace => fork vXMain module onlyUntil upstream mergesPatching a bug
excludeMain module onlyUntil a fixed version existsA known bad release
retractPublisherForever (history)A tag you published by mistake
go work useYour workspaceLocal onlyReplacing 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.

txt
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.

module academy/shop (directory with go.mod; module path = import path prefix)cmd/apipackage main -> binarycmd/workerpackage main -> binarypkg/moneyexported APIinternal/storeprivate to moduleinternal/orderspackage ordersinternal/httppackage httpgo.mod go.sum (module root only)vendor/ (optional copy of dependencies)import "academy/shop/internal/orders" OK inside academy/shop/...import "academy/shop/internal/orders" from another module: use of internal package not allowed
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 compiler

What 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.

go
// 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)
}
go
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 toolBoundaryEnforced byError
Capital letterPackageCompilerundefined: strings.toLower (but have ToLower)
internal/ directoryModule subtreego commanduse of internal package ... not allowed
Unexported fieldPackageCompilerg.prefix undefined (type *greet.Greeter has no field or method prefix)
_test packageTest codeCompilerOnly exported API compiles
Separate moduleVersion contractSemantic import versioningBreaking 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.

Imported packagevars, then init()Imported packagevars, then init()Package mainvars in dependency orderPackage maininit() functions, file ordermain.main()your program runsDepth-first by import graph; a package is initialised once, after everything it importsNever rely on the order between sibling packages; sort or register explicitly.
go
// 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") }
go
package initorder

var c = record("var c in second.go")

func init() { record("init in second.go") }
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.

go
// 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 }
go
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).

go
// 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())
}
go
// 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())
}
go
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
//go:build debug

package platform

const flavour = "debug"
go
//go:build !debug

package platform

const flavour = "release"
go
package platform

// The _windows suffix is an implicit constraint: only GOOS=windows compiles this file.
const osName = "windows"
ToolExampleEffect
Tag expression//go:build !debugFile compiled unless -tags debug
OS suffixos_windows.goOnly GOOS=windows
Arch suffixhash_arm64.goOnly GOARCH=arm64
Combined suffixx_linux_arm64.goBoth
Version tag//go:build go1.24Compiler at least 1.24
Test-onlyintegration_test.go with //go:build integrationRuns with go test -tags integration
Per-file language//go:build go1.22Also 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
VariableTypical valuesNotes
GOOSlinux, darwin, windows, freebsd, js, wasip1js/wasm, wasip1/wasm for WebAssembly
GOARCHamd64, arm64, 386, arm, riscv64, wasmGOARM=7 for 32-bit ARM
CGO_ENABLED0 or 1Default 1 when a C compiler exists and not cross-compiling
GOAMD64v1 to v4Instruction-set level
GOARM64v8.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.

sh
#!/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
FlagEffectMeasured here
noneDebug info and local paths in the binary2,605,186 bytes
-ldflags='-s -w'Strip symbols and DWARF1,705,570 bytes
-trimpathRemove /Users/... from pathsTwo copies in different directories get the same SHA-256
-X pkg.Var=valSet string at link timev1.2.3 printed by -version
-buildvcs=falseNo vcs.* settingsNeeded for dirty or non-git trees
-raceRace detector buildLarger, 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.

go
// 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)
}
go
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.

sql
-- 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:

sql
-- 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:

VariableTypical valuePurpose
GOROOT/opt/homebrew/Cellar/go/1.27.4/libexecThe installed toolchain
GOPATH~/goParent of bin/ and pkg/mod
GOBINemptyWhere go install writes; defaults to $GOPATH/bin
GOMODCACHE~/go/pkg/modUnpacked module versions; files are read-only (use -modcacherw to change)
GOCACHEOS cache dirCompiled package and test cache
GOENV~/Library/Application Support/go/envThe file go env -w writes
GOWORKempty or a pathActive go.work
GOFLAGS, GOPROXY, GOSUMDB, GOPRIVATE, GOTOOLCHAINsee aboveBehaviour
GOOS, GOARCH, CGO_ENABLEDhost valuesBuild 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.

MessageMeaningFix
no required module provides package golang.org/x/text/language; to add it: go get golang.org/x/text/languageImport has no require in go.modgo 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/demogo.sum incompletego 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 allowedTwo packages import each otherExtract shared types, or invert with an interface
use of internal package example.com/lib/internal/secret not allowedImporter is outside the parent treeMove code, or expose a public package
undefined: strings.toLower (but have ToLower)Lowercase name from another packageUse the exported name
package example.com/nm is not a main packagego run of a libraryRun a package main directory
go: go.mod requires go >= 1.99 (running go 1.27.4; GOTOOLCHAIN=local)Toolchain too old and switching offInstall it or allow auto
go: download go1.99.0 for darwin/arm64: toolchain not availableNo such toolchain existsFix 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/libreplace without requireAdd the require line
go: updates to go.mod needed; to update it: go mod tidyRead-only mode needs an editRun go mod tidy
go: -mod may only be set to readonly or vendor when in workspace mode-mod=mod inside a workspaceGOWORK=off or drop the flag
SECURITY ERROR ... checksum mismatch (documentation)Downloaded bytes differ from go.sum or the checksum databaseDo not bypass; investigate
go: errors parsing go.mod (documentation)Syntax error in go.modFix 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
ToolAnswersOutput shape
go list -m allWhich versions are in the build?path version per line
go list -m -u allWhich have newer versions?Adds [v1.5.0]
go list -m -versions xWhich versions exist?One line
go list -deps ./cmd/helloWhich packages are compiled?Import paths
go list -f '{{.ImportPath}} {{.Name}}' ./...Package names per directoryTemplate
go mod graphWho requires whom?from to edges
go mod why -m xWhy is x needed?Chain

Static versus cgo, and what a go build embeds Good to know ​

PropertyCGO_ENABLED=1CGO_ENABLED=0
Binary links libc dynamically (Linux)Often, for net and os/userNo: fully static
Needs gcc or clangYesNo
Cross-compile with GOOS/GOARCH onlyNo (needs a cross C compiler)Yes
DNS resolvercgo resolver by default on some OSesPure Go resolver
SQLite via mattn/go-sqlite3WorksFails; use a pure Go driver
Image FROM scratchNeeds libcWorks

Solving the classic problems ​

ProblemSolutionHowCost
New dependency in codeTidygo mod tidy then commit both filesA network fetch
Edit a dependency while testingWorkspacego work init . ../libDo not commit go.work
Fix a dependency now, upstream laterReplace to a forkreplace x => github.com/you/x v1.2.3-fixMaintain the fork
Private repositoriesMark privateGOPRIVATE=git.corp/* and git credentialsLose proxy cache for them
Offline or locked-down CIVendorgo mod vendor, -mod=vendor, commit vendor/Big diffs
Version in --versionStamp-ldflags "-X pkg.Version=$VERSION"Build script
Same bytes everywhereReproducible build-trimpath, CGO_ENABLED=0, pinned toolchain, no -buildvcs surprisesDiscipline
Build for another platformCross-compileGOOS=linux GOARCH=arm64 CGO_ENABLED=0 go buildcgo is off
Two binaries, shared codecmd/ plus internal/One module, many mainsShared release cadence
Break a package cycleInterface at the boundaryDefine the interface where it is usedOne 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 type

Real 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 ​

SituationChooseExtra techniqueReason
Single serviceOne module, cmd/<name>, internal/go 1.24 plus a toolchain lineLeast ceremony
Several services owned by one teamOne module, many cmd/internal/ for shared codeOne version, atomic changes
Library you publishOne module at repo rootSemantic versions, retract on mistakesConsumers get MVS
Two repos changing togetherWorkspaceGOWORK=off in CINo replace commits
Strict supply chainVendor plus GOFLAGS=-mod=vendorgo mod verify, GOFLAGS=-mod=readonlyOffline and reviewable
Many teams and a mono-repoOne module per team boundaryWorkspaces locallyIndependent versions
Release binariesCGO_ENABLED=0, -trimpath, -ldflagsPin GOTOOLCHAINSame bytes, small image
Tool needed by developerstool directive and go toolgo get -toolPinned versions without tools.go
Need a C libraryCGO_ENABLED=1 in a matching build imageBuild per target nativelyCross 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 / ComposerGo
composer.json requirego.mod require
composer.lockgo.sum verifies; the build list is derived
composer updatego get -u ./...
composer installgo build (downloads on demand)
autoload PSR-4 namespacesImport path = directory path
private/protected/publicCapital letter; internal/
config/app.php bootstrapping, service providers boot()Explicit constructors from main; avoid init()
php artisan commandscmd/<name> binaries
php
// 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.0

Go ​

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× ​

ScaleToolchain and modulesWhat changes
1× (one developer)go run, no proxy configNothing to manage
10× (a team)toolchain line, go.sum committed, CI go vet, go test -racePinning and gates
100× (many teams)Internal proxy, GOPRIVATE, GOFLAGS=-mod=readonly, vendoring or module mirror, govulncheck on ReadBuildInfoSupply-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=darwin
  1. Stamp and inspect, as above. Expected: -version prints the injected values.

  2. 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
  1. 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
  1. 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
  1. 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
  1. 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
  1. 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
  1. Vendor: go mod vendor wrote vendor/modules.txt listing # golang.org/x/text v0.44.0, ## explicit; go 1.26.0 and 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 ​

BeliefReality
go.sum is a lock fileThe build list comes from go.mod through MVS; go.sum only verifies bytes
Go always picks the newest dependencyIt picks the highest version required by anyone; newer releases are ignored until requested
go 1.24 is the toolchain that buildsIt is a minimum and the language version; toolchain and GOTOOLCHAIN decide the compiler
go build fetches missing importsNot since Go 1.16; run go get or go mod tidy
replace in my library fixes my users' buildsOnly the main module's replace counts
A tag v2.0.0 is enough for a major versionThe module path needs /v2 and every import must include it
init() is a safe place for setupIt cannot fail cleanly, runs in every test binary and hides order dependencies
Cross-compiling needs special compilersPure Go needs only GOOS/GOARCH; only cgo needs a C cross-compiler
internal/ is a conventionThe go command rejects the import with an error
The package name must equal the directory nameOnly the package clause counts; it conventionally matches
go run leaves a binaryIt builds into a temp directory and deletes it
Workspaces make the published build differentgo.work is local; CI should build with GOWORK=off

Cheat sheet ​

TopicWhat to remember
New projectgo mod init example.com/app, then go mod tidy after imports change
Daily loopgo run, go test ./..., go vet ./..., gofmt -l .
Release buildCGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X pkg.Version=$V" ./cmd/x
Toolchaingo line = minimum; toolchain = suggestion; GOTOOLCHAIN = policy
Dependenciesgo get pkg@v1.2.3, go get -u ./..., go mod tidy, commit go.mod and go.sum
Why is it herego mod why -m x, go mod graph, go list -m all
Local developmentgo work init; never commit a replace => ../x
Private modulesGOPRIVATE=git.corp/* plus git credentials
Major versions/v2 in module and in imports; +incompatible otherwise
VisibilityCapital letter = package export; internal/ = module-tree export
init()Registration only; blank import for drivers
Multi-binarycmd/<name>/main.go; share code under internal/
Build tags//go:build tag above package; _linux.go suffixes
Build infodebug.ReadBuildInfo(), go version -m binary
Errorsmissing go.sum entry -> tidy; import cycle -> interface or extract; internal -> move

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ModuleA tree of packages released together, rooted at a directory with go.mod
Module pathThe name in the module line; prefix of every import path in the module
PackageA directory of .go files sharing a package clause; unit of compilation and visibility
Import pathModule path plus relative directory, as written in import
go directiveMinimum Go version and language version for the module
toolchain directiveSuggested toolchain; a floor, not a ceiling
GOTOOLCHAINPolicy for choosing or downloading the toolchain: auto, local, path, or a version
requireMinimum version of a dependency
replaceSubstitute a module or version with another module or directory (main module only)
excludeForbid a specific module version
retractThe publisher's declaration that versions must not be used
go.sumFile of cryptographic hashes verifying downloaded modules
Checksum databasesum.golang.org, the public transparent log of module hashes (GOSUMDB)
GOPROXYOrdered list of module proxies; direct means version control
GOPRIVATEPrefixes treated as private; implies GONOPROXY and GONOSUMDB
GONOSUMDBPrefixes excluded from checksum database lookups
GOFLAGSDefault flags for every go command
Minimal version selectionAlgorithm that selects the highest version required in the graph
Build listThe module versions MVS chooses; printed by go list -m all
Semantic import versioningMajor versions 2+ add /vN to the module and import paths
Pseudo-versionVersion for an untagged commit: base, UTC timestamp, 12-char hash
+incompatibleSuffix for v2+ tags in a repository without go.mod
Workspace / go.workA set of local modules treated as main modules together
Exported identifierA name starting with an upper-case letter, visible to other packages
Internal packageA package under an internal/ directory, importable only from the parent tree
init()A function run automatically during package initialisation; cannot be called
Blank importimport _ "path"; imports only for init() side effects
cmd/Conventional directory holding one package main per binary
Build tag / //go:buildA constraint that includes or excludes a file from a build
GOOS, GOARCHTarget operating system and CPU architecture
CGO_ENABLEDWhether C code may be linked; 0 gives static, cross-compilable binaries
-ldflags -XLinker flag that sets a package-level string variable
-trimpathCompiler flag that removes file system paths from the binary
Reproducible buildSame inputs produce byte-identical binaries
ReadBuildInforuntime/debug function returning embedded build metadata
Module cache / GOMODCACHEDirectory with downloaded, read-only module versions
Vendor directoryOptional copy of dependencies inside the module (vendor/)
Import cycleTwo packages importing each other, forbidden by the compiler

References ​

Built by Morteza Negahi