Overview
go build compiles packages, go run builds-and-executes in one step (dev loop), and
go install builds a binary into GOPATH/bin — the standard way to install Go tools
(go install tool@version). All three share the content-addressed build cache, so
"incremental builds" need no configuration: unchanged packages are never recompiled.
Key points
- Build cache: keyed by hashes of source, flags, and toolchain; lives in
go env GOCACHE;go clean -cachewipes it. Correct by construction — nomake cleanrituals. - Build tags & file suffixes:
//go:build linux && amd64constraints and the_linux.go/_amd64.go/_test.gofilename conventions select files per target; this is how the standard library does platform-specific code. -ldflags "-s -w"strips symbol table and DWARF for smaller binaries;-X importpath.Var=valuestamps version/commit strings intovardeclarations at link time — the idiomatic version-injection mechanism.-trimpathremoves local filesystem paths from the binary for reproducible builds.- Cross-compilation is a variable, not a project:
GOOS=linux GOARCH=arm64 go buildworks from any host with no extra toolchain;go tool dist listprints the full matrix. CGO is disabled by default when cross-compiling, keeping binaries static. -racebuilds with the race detector (needs CGO on most platforms); slower and hungrier, but the standard CI gate for concurrent code.- PGO (1.21+): drop a CPU profile as
default.pgonext tomainand builds apply profile-guided optimization automatically — typically low-single-digit percent wins. go runis not deployment: it recompiles into a temp location; shipgo buildartifacts.
Examples
# Static linux binary with version stamped in, reproducible paths
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags "-s -w -X main.version=$(git describe --tags)" -o bin/app ./cmd/app
go install golang.org/x/vuln/cmd/govulncheck@latest # install a tool
Related
- The Go toolchain — parent catalog; the environment variables these commands read.
- go test — same build machinery producing test binaries.
- Building & releasing — release pipelines (goreleaser, containers) around these commands.
- Compilers & runtimes — the gc compiler these commands invoke.