Packages and modules
How Go code is cut into packages, how packages start, and how the go command picks each version of each dependency. Every output on this sheet comes from the real go command, run against a private proxy.
- 1A package is a folder and the unit of import. A module is a tree of packages and the unit of version.
- 2Initialization follows dependencies, not source order. Do not depend on anything else.
- 3Minimal version selection takes the highest version that any go.mod asks for. A new release changes nothing by itself.
- 4replace and exclude work only in the main module. A library cannot force them on you.
package main
import (
"fmt"
"example.com/shop/alpha"1
"example.com/shop/beta"
)
func init() { fmt.Println("main init") }
func main() {
fmt.Println("main", alpha.Name, beta.Name)
}- 1Listed first, and it does not run first.
$ go run .
beta init: beta
zeta init: zeta
alpha init: alpha+zeta
main init
main alpha+zeta betapackage alpha
import (
"fmt"
"example.com/shop/zeta"1
)
var Name = "alpha+" + zeta.Name
func init() { fmt.Println("alpha init:", Name) }- 1alpha must wait for zeta.
package beta
import "fmt"
var Name = "beta"1
func init() { fmt.Println("beta init:", Name) }- 1beta imports only fmt, so it is ready first. zeta has the same shape as beta.
- Since 1.21 the go tool sorts packages by import path. It then takes the first package whose imports are done.
- alpha sorts first but is not ready. beta is ready, so beta runs. Then zeta, then alpha, then main.
Initialization order follows the import graph. If two packages have no link, sorted import path decides, so I never rely on it.
I version a module, I import a package, and I select a file with build constraints.
| rule | example | status |
|---|---|---|
| Short, lower case, one word, no underscore | orders, tax, http | Approved |
| Name it for what it provides | cache.Get, not data.GetCache | Approved |
| Do not repeat the package name in exports | http.Server, not http.HTTPServer | Approved |
| Keep main small: parse flags, wire, run | cmd/api/main.go | Approved |
| Start with internal/, and export only on demand | internal/store | Approved |
| Define an interface in the package that consumes it | orders.Store | Approved |
| Split a package when two parts change for different reasons | orders, billing | Not by type |
| A package that names nothing | util, common, helpers | Not approved |
| One package per type, in the Java style | models, services | Not approved |
| An import cycle; the compiler refuses it | a imports b imports a | Move the shared part |
A package name is a word that reads well before the dot. If the best name is util, the package has no single job.
$ go build -o /dev/null .
package example.com/shop
main.go:6:2: use of internal package example.com/secure/internal/pay not allowed$ go build ./orders/...
$ go build ./billing
package example.com/shop/billing
billing/billing.go:3:8: use of internal package example.com/shop/orders/internal/tax not allowed- orders/internal/tax is open to orders and to orders/api. billing is a sibling, so the build fails.
- Use it to keep a public API small: you can change internal code with no major version.
A package under internal is importable only from the tree rooted at the parent of internal. The go command enforces it, also inside one module.
| step | rule | status |
|---|---|---|
| 1 | Each package initializes once, after all of its imports, however many packages import it. | Approved |
| 2 | Package variables start in declaration order. A variable waits for each variable that it refers to, also through a function. | Approved |
| 3 | Then init functions run. A package can have many, and no code can call them. | Approved |
| 4 | All of this runs in one goroutine. main.main starts after every init returns. | Approved |
| use | Register a driver or a codec in init, through a blank import. | Standard pattern only |
| use | A dependency hidden by an interface call. The spec leaves that order open. | Not approved |
| use | I/O, flags or network calls in init. A test cannot skip them, and a failure can only panic. | Not approved |
Each package initializes once: imports first, then variables by dependency, then each init. I keep init small and free of I/O.
Step 1: Main module
- Start at the main module, which has no version.
- Each require line is a minimum: a v1.2.0 or higher, b v1.2.0 or higher.
If it fails
A go.sum entry that is missing stops the command. The go command does not add one in a read-only build.
MVS walks the graph and keeps the highest version that anyone required. There is no solver and no lock file, so the build list is the same tomorrow.
| change | a | b | c | d | why |
|---|---|---|---|---|---|
| Nothing | v1.2.0 | v1.2.0 | v1.4.0 | v1.2.0 | The highest that any go.mod asks for. |
| go get [email protected] | v1.2.0 | v1.2.0 | v1.5.0 | v1.3.0 | c v1.5.0 needs d v1.3.0, so d moves too. |
| go get [email protected] | v1.2.0 | v1.1.0 | v1.3.0 | v1.2.0 | b v1.2.0 needs c v1.4.0, so b moves down. |
| exclude c v1.4.0 | v1.2.0 | v1.2.0 | v1.3.0 | v1.2.0 | The requirement is ignored, so b runs below what it asked for. |
| replace c => ./forks/c | v1.2.0 | v1.2.0 | v1.4.0 => ./forks/c | v1.2.0 | The version stays. The code comes from the folder. |
$ go list -m all
example.com/shop
example.com/c v1.3.0
example.com/d v1.1.0
example.com/e v1.0.0
$ go run .
e v1.0.0 > c v1.3.0 > d v1.1.0$ go list -m all
example.com/shop
example.com/a v1.2.0
example.com/b v1.2.0
example.com/c v1.4.0 => ./forks/c
example.com/d v1.2.0
$ go run .
a v1.2.0 > c forked > d v1.2.0
b v1.2.0 > c forked > d v1.2.0Upgrades move one path and what it needs. exclude and replace change the graph, and they apply only in the main module.
// Version is one release of a module, such as {"C", 3} for C v1.3.0.
type Version struct {
Path string
Minor int
}
// Graph maps each module version to the versions it requires.
type Graph map[Version][]Version
// BuildList walks everything reachable from main, and keeps the highest
// version it sees of each path. No solver runs, and no choice is made.
func BuildList(g Graph, main Version) []Version {
best := map[string]int{}
seen := map[Version]bool{}
var walk func(v Version)
walk = func(v Version) {
if seen[v]2 {
return
}
seen[v] = true
best[v.Path] = max(best[v.Path], v.Minor)1
for _, dep := range g[v] {
walk(dep)
}
}
walk(main)
delete(best, main.Path)3
list := make([]Version, 0, len(best))
for _, path := range slices.Sorted(maps.Keys(best)) {
list = append(list, Version{path, best[path]})
}
return list
}- 1The only decision: keep the highest version seen for each path.
- 2The graph can contain cycles, so stop at a version already visited.
- 3The main module has no version, and it is not in the list.
The whole algorithm is a graph walk with a max per path. I can write it on a whiteboard.
module example.com/shop1
go 1.272
require (
example.com/a v1.2.0
example.com/b v1.2.0
)
require (
example.com/c v1.4.0 // indirect3
example.com/d v1.2.0 // indirect
)- 1The import path prefix of each package here.
- 2The language version, and the minimum toolchain.
- 3No package here imports c directly. This line lets the go command skip deeper go.mod files.
example.com/shop example.com/[email protected]
example.com/shop example.com/[email protected]
example.com/shop example.com/[email protected]
example.com/shop example.com/[email protected]
example.com/shop [email protected]
example.com/[email protected] example.com/[email protected]
example.com/[email protected] example.com/[email protected]
example.com/[email protected] [email protected]
example.com/[email protected] example.com/[email protected]
example.com/[email protected] example.com/[email protected]
example.com/[email protected] [email protected]
example.com/[email protected] example.com/[email protected]
example.com/[email protected] [email protected]
example.com/[email protected] [email protected]
[email protected] [email protected]Direct and indirect requirements sit in two blocks. The indirect block is what makes graph pruning work.
| directive | what it does | applies in | since |
|---|---|---|---|
| module | The path of this module. | Every module | |
| go | Language version and minimum toolchain. A strict minimum since 1.21. | Every module | 1.21 |
| toolchain | A suggested toolchain, not below the go line. | Main module | 1.21 |
| godebug | GODEBUG defaults for this build. | Main module | 1.23 |
| require | A minimum version of a dependency. | Every module | |
| tool | A package to run with go tool. Needs a require line. | Main module | 1.24 |
| ignore | Folders that package patterns skip. They stay in the module zip. | This module | 1.25 |
| exclude | A version that must not load. | Main module only | |
| replace | Other code for a version: a fork, or a local path. | Main module only | |
| retract | Marks your own bad releases, so go get avoids them. | The latest version of that module |
require is a minimum. replace and exclude are local to the main module. tool and ignore are newer, and they remove old workarounds.
$ cat go.sum
example.com/a v1.2.0 h1:YSwjZ5JwWj2yBGTNtMwdfAYUu4yZIINu5/wQIz0nRrE=
example.com/a v1.2.0/go.mod h1:daNonZL2PaAIl/yidmaNSrA/6BPWJsETeMBiOnsWQ8M=
example.com/b v1.2.0 h1:iNVB2uf7L3pGDab8VKaHJPboZFFbXB0mkHOukwUIBeg=
example.com/b v1.2.0/go.mod h1:MQw/MJYoqpiCbgkCcl+gAoFRuNP8wzTwEeYmbdRvLfQ=
example.com/c v1.4.0 h1:0CprvYQtt0CBtZc2K7L3S02DhJMrgwjogjcyWFJbDI8=
example.com/c v1.4.0/go.mod h1:Ag7GF220kK80oroB+j27GMiNDuNUVuX4lEt3XUw4NFo=
example.com/d v1.2.0 h1:pNf5YhI8SI0DxS2MPYemzyRWSrW4+KL5t71yWWBOiKw=
example.com/d v1.2.0/go.mod h1:ChwSNrGUE67ZT+15RcIKm3aoo8UU74op9eTKN5AqaoY=$ go build -o /dev/null .
go: downloading example.com/a v1.2.0
go: downloading example.com/b v1.2.0
go: downloading example.com/c v1.4.0
verifying example.com/[email protected]: checksum mismatch
downloaded: h1:rqPegbOuaEtqhObzlzcrWotGgajm+kiFiP7GS8X8euk=
go.sum: h1:0CprvYQtt0CBtZc2K7L3S02DhJMrgwjogjcyWFJbDI8=
SECURITY ERROR
This download does NOT match an earlier download recorded in go.sum.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.
For more information, see 'go help module-auth'.- A version is immutable. The same module and version must have the same hash on every machine.
- Commit go.sum. It can hold more lines than the build list, and go mod tidy removes the extra ones.
go.sum is not a lock file. It holds hashes of what I already trust, so a changed release stops the build.
$ go get -tool example.com/hello/cmd/hello
go: downloading example.com/hello v1.0.0
go: added example.com/hello v1.0.0
$ cat go.mod
module example.com/shop
go 1.27
tool example.com/hello/cmd/hello
require example.com/hello v1.0.0 // indirect
$ go tool hello
hello from a toolA build tool is now a dependency in go.mod, so each developer and CI run the same version. The tools.go file can go.
$ (in svc) go run .
lib published v1.0.0
$ go work init ./svc ./lib
$ cat go.work
go 1.27.3
use (
./lib
./svc
)
$ (in svc) go run .
lib local edit
$ (in svc) go run .
lib published v1.0.0The last run sets GOWORK=off. The go.mod files never change.
A workspace lets me change a library and a service together with no replace line. I do not commit go.work for a library.
| file | linux/amd64 | linux/arm64 | darwin/arm64 | windows/amd64 | linux/amd64 -tags pro | why |
|---|---|---|---|---|---|---|
| app.go | In | In | In | In | In | No constraint. |
| linux.go | In | In | In | In | In | A name with no underscore has no constraint. |
| app_unix.go | In | In | In | In | In | unix is not a file suffix, so this has no constraint. |
| app_linux.go | In | In | Out | Out | In | Suffix _GOOS. |
| app_windows.go | Out | Out | Out | In | Out | Suffix _GOOS. |
| app_amd64.go | In | Out | Out | In | In | Suffix _GOARCH. |
| app_linux_arm64.go | Out | In | Out | Out | Out | Suffix _GOOS_GOARCH. |
| tag_unix.go | In | In | In | Out | In | //go:build unix: the unix tag does exist. |
| pro.go | Out | Out | Out | Out | In | //go:build pro, set with -tags pro. |
| free.go | In | In | In | In | Out | //go:build !pro. |
| future.go | Out | Out | Out | Out | Out | //go:build go1.99: newer than this toolchain. |
| gen.go | Out | Out | Out | Out | Out | //go:build ignore: only go run gen.go uses it. |
| app_test.go | Out | Out | Out | Out | Out | Only go test compiles it. |
A _linux or _amd64 suffix is a build constraint. There is no _unix suffix, so for that I use a //go:build unix line.
$ go build -o /dev/null .
# example.com/shop
./main.go:7:27: undefined: generated
$ go generate -x
go run gen.go
$ cat names_gen.go
// Code generated by gen.go; DO NOT EDIT.
package main
const generated = "made by go generate"
$ go run .
made by go generate- The go tool scans source for //go:generate lines and runs each one. It does no dependency analysis.
- go build ignores these lines, so the first build fails.
- The line "Code generated ... DO NOT EDIT." marks a file as generated for tools.
- The generator here has //go:build ignore, so it stays out of the package.
- Pin a generator with a tool directive: //go:generate go tool stringer.
go generate is a command I run by hand, and go build never runs it. I commit the output, so users need no generator.
$ go mod vendor
$ cat vendor/modules.txt
# example.com/a v1.2.0
## explicit; go 1.27
example.com/a
# example.com/b v1.2.0
## explicit; go 1.27
example.com/b
# example.com/c v1.4.0
## explicit; go 1.27
example.com/c
# example.com/d v1.2.0
## explicit; go 1.27
example.com/d
$ go run .
a v1.2.0 > c v1.4.0 > d v1.2.0
b v1.2.0 > c v1.4.0 > d v1.2.0
$ go run .
go: inconsistent vendoring in .:
example.com/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
example.com/[email protected]: is marked as explicit in vendor/modules.txt, but not explicitly required in go.mod
To ignore the vendor directory, use -mod=readonly or -mod=mod.
To sync the vendor directory, run:
go mod vendor| situation | status |
|---|---|
| Builds with no network, or a rule that all source sits in the repository | Approved |
| A vendor folder at the module root, with a go line of 1.14 or later | Used automatically |
| A normal service that reaches a proxy | Not needed |
| A vendor folder inside a dependency | Ignored |
I vendor when a build must run with no network. If go.mod and vendor disagree, the go command stops.
| setting | default | what it does |
|---|---|---|
| GOPROXY | https://proxy.golang.org,direct | Tries each entry in turn. direct means the version control server. |
| GOSUMDB | sum.golang.org | A transparent log of go.sum lines. Auditors can check that it does not change. |
| GOPRIVATE | empty | Glob patterns of private paths. The default for GONOPROXY and GONOSUMDB. |
| GONOPROXY | GOPRIVATE | Paths that skip the proxy. |
| GONOSUMDB | GOPRIVATE | Paths that skip the public checksum database, so their names stay private. |
| GOAUTH | netrc | How private fetches authenticate, since 1.24. |
The proxy serves bytes and the checksum database proves them, so a proxy cannot change code unnoticed. For private code I set GOPRIVATE.
| go.mod | GOTOOLCHAIN | recorded result | status |
|---|---|---|---|
| go 1.21.0 | local | go1.27.3 | A newer toolchain runs older code |
| go 1.99.0 | local | go: go.mod requires go >= 1.99.0 (running go 1.27.3; GOTOOLCHAIN=local) | A strict minimum |
| go 1.27.0, toolchain go1.99.0 | local | go1.27.3 | The line is only a suggestion |
| go 1.27.0, toolchain go1.99.0 | auto | go: download go1.99.0 for darwin/amd64: toolchain not available | Tries to download it |
| go 1.27.0, godebug asynctimerchan=1 | local | go.mod:5: removed GODEBUG "asynctimerchan" set to old value "1" (https://go.dev/doc/godebug#go-127) | Support removed in 1.27 |
- Our own lab module has the line go 1.27.3 and no toolchain line. Inside it, a go 1.26.2 command downloads 1.27.3 and runs it, with GOTOOLCHAIN=auto, the default.
- Selection order with auto: a newer toolchain line, then a newer go line, then the bundled toolchain.
- go get [email protected] raises the go line, and go get toolchain@patch raises only the suggestion.
- Since 1.25, a go line update no longer adds a toolchain line.
- GODEBUG=toolchaintrace=1 prints the steps of the selection, since 1.24.
The go line is a minimum, and the toolchain line is a suggestion for the main module. With GOTOOLCHAIN=auto the go command switches for me.
| since | what changed | what it means here |
|---|---|---|
| 1.21 | The go line is a strict minimum. New toolchain line, with toolchain download. Package initialization order is specified. | An older toolchain refuses the module and does not guess. |
| 1.22 | go work vendor. go mod init no longer reads config files of older vendoring tools. | A workspace can build with no network. |
| 1.23 | godebug block in go.mod and go.work. go mod tidy -diff. go vet stdversion. | Use tidy -diff in CI: it exits non-zero when go.mod needs a change. |
| 1.24 | tool directive, go get -tool, tool pattern. GOAUTH. The main module version comes from the VCS tag. toolchaintrace=1. | Delete tools.go. |
| 1.25 | ignore directive. work package pattern. A module root can be a subfolder of a repository. No automatic toolchain line. | go.mod diffs get smaller. |
| 1.26 | go mod init writes a go line one release behind the toolchain. | New modules work on supported versions by default. |
| 1.27 | go mod tidy keeps two require blocks. A removed GODEBUG setting with an old value is an error. | Resolve an old setting before you move to 1.27. |
| when | the moment | what to do or say |
|---|---|---|
| build | Starting from an empty folder. | Run go mod init, then write one package main. Split only when a second concept appears. |
| build | Handler, service and store in 45 minutes. | Use a few files in one package, or three short packages under internal/. Do not design a tree. |
| build | A global map set up at start. | Build it in a constructor in main, not in init. Tests can then make their own. |
| talk | "Why does Go have no lock file?" | MVS is deterministic: the build list comes from go.mod files, and they do not change when a new release appears. |
| talk | "A dependency has a security fix." | Run go get on that module at the fixed version, then go mod tidy. Check that go list -m all shows it. |
| talk | "A library breaks in a new version." | Stay at the old version, or use replace with a fork. A library cannot pass a replace to its users. |
| talk | "How do you make builds reproducible?" | Commit go.mod and go.sum, set the go line, and pin tools with tool directives. Vendor if the build has no network. |
| talk | "How do you use private modules?" | Set GOPRIVATE, so that the paths skip the proxy and the checksum database. Authenticate through Git or GOAUTH. |
| talk | "When is a monorepo one module?" | One module gives one version of each dependency. Use a workspace when teams need separate modules. |
I keep the build flat and simple, and I can explain each line of go.mod when asked.
0 of 10 known
Predict the output.
package main import "fmt" var a = trace("a", b+1) var b = trace("b", c+1) var c = trace("c", 1) func trace(name string, v int) int { fmt.Println(name, v) return v } func main() { fmt.Println("main", a) }Predict the output.
package main import "fmt" var total = sum() var prices = load() func load() []int { fmt.Println("load") return []int{2, 3} } func sum() int { fmt.Println("sum") n := 0 for _, p := range prices { n += p } return n } func main() { fmt.Println(total) }Predict the output. Compare it with the question before.
package main import "fmt" type Getter interface{ Get() int } type source struct{} func (source) Get() int { return v } var g Getter = source{} var x = trace("x", g.Get()) var v = trace("v", 7) func trace(name string, n int) int { fmt.Println(name, n) return n } func main() { fmt.Println(x, v) }Predict the output.
package main import "fmt" var ready = announce() func announce() bool { fmt.Println("var") return true } func init() { fmt.Println("init 1", ready) } func init() { fmt.Println("init 2") } func main() { fmt.Println("main") }Predict the output.
package main import "fmt" func init() { fmt.Println("start") panic("boot failed") } func main() { fmt.Println("main") }Predict the output. Compare it with the G1 drill on panic(nil).
//go:debug panicnil=1 package main import "fmt" func main() { defer func() { fmt.Println(recover()) }() panic(nil) }You run go get example.com/[email protected]. Predict the new build list.
shop needs a v1.2.0, b v1.2.0 a v1.2.0 needs c v1.3.0 b v1.2.0 needs c v1.4.0 c v1.4.0 needs d v1.2.0 published: c v1.5.0 (needs d v1.3.0)You run go get example.com/[email protected], below what b v1.2.0 needs. Predict the result.
shop needs a v1.2.0, b v1.2.0 a v1.2.0 needs c v1.3.0 b v1.2.0 needs c v1.4.0 c v1.4.0 needs d v1.2.0 published: c v1.5.0 (needs d v1.3.0) b v1.1.0 needs c v1.2.0You add exclude example.com/c v1.4.0, then run go mod tidy. Predict the build list.
shop needs a v1.2.0, b v1.2.0 a v1.2.0 needs c v1.3.0 b v1.2.0 needs c v1.4.0 c v1.4.0 needs d v1.2.0 published: c v1.5.0 (needs d v1.3.0)Module e has its own line: replace example.com/c => example.com/c v1.5.0. Your module requires e, and e requires c v1.3.0. Predict the build list.
require example.com/e v1.0.0