The go command is the primary tool for managing Go source code. It provides a unified interface for compiling packages, running tests, managing dependencies, and executing Go programs. This document covers the command-line interface, command structure, action graph construction, and build execution mechanisms.
For information about the module system and dependency resolution, see Module System. For details about package loading and resolution, see Package Loading. For linker implementation, see Linker.
Sources: src/cmd/go/alldocs.go1-60
The go command implements a subcommand architecture where each major operation (build, test, run, etc.) is implemented as a separate subcommand with its own flags and behavior.
Each command is represented by a base.Command structure that defines:
UsageLine: Command syntaxShort: Brief descriptionLong: Detailed documentationRun: Execution functionFlag: Command-specific flagsSources: src/cmd/go/internal/base/base.go src/cmd/go/internal/work/build.go29-239
| Command | Purpose | Key Flags |
|---|---|---|
go build | Compile packages and dependencies | -o, -a, -n, -x, -race |
go install | Compile and install packages | Same as build |
go run | Compile and run Go program | -exec |
go test | Test packages | -v, -run, -bench, -cover |
go clean | Remove object files and cached files | -cache, -testcache, -modcache |
Sources: src/cmd/go/alldocs.go71-341 src/cmd/go/internal/work/build.go29-239
| Command | Purpose | Output |
|---|---|---|
go list | List packages or modules | Package metadata |
go env | Print Go environment information | Environment variables |
go doc | Show documentation | Package/symbol docs |
go version | Print Go version | Version string |
Sources: src/cmd/go/internal/list/list.go37-46 src/cmd/go/internal/envcmd/env.go36-64
| Command | Purpose |
|---|---|
go tool | Run specified go tool |
go vet | Report likely mistakes in packages |
go fix | Apply fixes suggested by static checkers |
go fmt | Gofmt (reformat) package sources |
go generate | Generate Go files by processing source |
Sources: src/cmd/go/internal/tool/tool.go35-63 src/cmd/go/internal/vet/vet.go30-88
The build system constructs a directed acyclic graph (DAG) of actions that must be performed to build the requested packages. Each action represents a single unit of work (e.g., compile a package, link an executable).
Sources: src/cmd/go/internal/work/action.go1-156 src/cmd/go/internal/work/exec.go52-258
Each Action contains:
Key action types based on Mode:
"build": Compile a package"link": Link an executable"test binary": Build a test binary"run test": Execute tests"vet": Run static analysis"check cache": Verify cache validitySources: src/cmd/go/internal/work/action.go84-129
The Builder.Do method executes the action graph:
The execution uses a priority queue to prefer completing higher-level actions first, improving user experience by showing results sooner (e.g., test results appear as they complete rather than all at the end).
Sources: src/cmd/go/internal/work/exec.go72-258
Actions form a dependency graph where an action cannot execute until all its dependencies complete:
The pending counter tracks how many dependencies remain. When an action completes, it decrements the pending counter of all actions in its triggers list. When pending reaches zero, the action becomes ready for execution.
Sources: src/cmd/go/internal/work/exec.go122-207
The build cache stores compiled packages and other build artifacts to avoid redundant work. It uses content-addressable storage based on action IDs.
The buildActionID function computes a cache key by hashing:
-gcflags, -ldflags, etc.)GOOS, GOARCH)Sources: src/cmd/go/internal/work/exec.go260-439
The cache directory structure (typically $GOCACHE):
-a flag (rebuild all)Cache benefits:
Sources: src/cmd/go/internal/work/exec.go518-636 src/cmd/go/internal/cache/default.go17-67
Before building, the go command must load package metadata including source files, imports, and build constraints.
Sources: src/cmd/go/internal/load/pkg.go1-56
The load.Package type represents a single package:
| Field | Type | Description |
|---|---|---|
Dir | string | Package source directory |
ImportPath | string | Import path |
GoFiles | []string | .go source files |
CgoFiles | []string | .go files with cgo |
Imports | []string | Import paths |
Internal.Imports | []*Package | Resolved package dependencies |
Target | string | Install path for compiled package |
Stale | bool | Whether package needs rebuilding |
Error | *PackageError | Load errors if any |
Sources: src/cmd/go/internal/load/pkg.go57-248
The actual compilation and linking is performed by invoking compiler and linker tools.
Sources: src/cmd/go/internal/work/exec.go721-1040
The gcToolchain.gc function compiles a package:
go tool compile \
-p <import-path> \
-lang=go1.21 \
-o <output.a> \
-trimpath <rewrites> \
-importcfg <import-map> \
-embedcfg <embed-config> \
<source-files...>
Key compiler flags:
-p: Package import path-lang: Go language version-importcfg: Maps import paths to compiled packages-embedcfg: Configuration for //go:embed directives-trimpath: Removes absolute paths from debug info-buildid: Build ID for caching-pack: Output archive formatSources: src/cmd/go/internal/work/gc.go56-180
The gcToolchain links executables:
go tool link \
-o <output-binary> \
-importcfg <import-map> \
-buildid=<build-id> \
<main-package.a>
The linker resolves symbols, applies relocations, and produces the final executable. For details on linker implementation, see Linker.
Sources: src/cmd/go/internal/work/gc.go
Build flags are shared across multiple commands (build, install, test, run, list) and are defined in the work package. Each command selectively enables the flags it supports.
Sources: src/cmd/go/internal/work/build.go240-260 src/cmd/go/internal/cfg/cfg.go69-114
Common build flags and their effects:
| Flag | Effect | Implementation |
|---|---|---|
-a | Force rebuild of all packages | Disables cache lookup |
-n | Print commands without executing | Sets cfg.BuildN |
-x | Print commands as executed | Sets cfg.BuildX |
-v | Print package names | Sets cfg.BuildV |
-race | Enable race detector | Adds race instrumentation |
-cover | Enable coverage | Instruments code with counters |
-trimpath | Remove file paths from binary | Rewrites paths during compilation |
Sources: src/cmd/go/internal/cfg/cfg.go69-114
The go command behavior is controlled by environment variables:
| Variable | Purpose | Default |
|---|---|---|
GOROOT | Go installation directory | Detected automatically |
GOPATH | Workspace directory | $HOME/go |
GOCACHE | Build cache directory | Platform-specific |
GOMODCACHE | Module cache directory | $GOPATH/pkg/mod |
GOOS | Target operating system | runtime.GOOS |
GOARCH | Target architecture | runtime.GOARCH |
CGO_ENABLED | Enable cgo | 1 if available |
Sources: src/cmd/go/internal/envcmd/env.go79-141
| Variable | Architectures | Purpose |
|---|---|---|
GOAMD64 | amd64 | Microarchitecture level (v1-v4) |
GOARM | arm | ARM version (5, 6, 7) |
GOMIPS | mips, mipsle | MIPS variant |
GOPPC64 | ppc64, ppc64le | PowerPC variant |
GORISCV64 | riscv64 | RISC-V variant |
These control code generation for specific processor features.
Sources: src/internal/buildcfg/cfg.go22-39
The go test command builds and runs tests, with special handling for test packages.
For a package with tests, the system creates:
*_test.go files (same package)package foo_test_testmain.go that calls all test functionsSources: src/cmd/go/internal/load/test.go102-155
Test results are cached based on:
-run, -short, etc.)Sources: src/cmd/go/internal/test/test.go1-179
Build actions execute shell commands through a Shell abstraction that handles output buffering, error reporting, and command logging.
The shell abstraction:
-n (dry-run) and -x (show commands) flagsSources: src/cmd/go/internal/work/shell.go
Build IDs uniquely identify build outputs and enable caching. Each compiled package has a build ID of the form actionID/contentID.
This separation enables:
Sources: src/cmd/go/internal/work/buildid.go1-63
Build IDs are stored:
Refresh this wiki