2. The toolchain and workspace
2.1 The commands you'll type every day
| Command | What it does |
|---|---|
go run . |
Compile to a temporary binary and run it |
go build |
Produce a binary for the current OS/arch |
go test ./... |
Run every test in the module |
go vet ./... |
Static analysis for correctness bugs (e.g. Printf format mismatches) |
go fmt ./... |
Reformat every file to the one canonical style |
go mod init <module> |
Start a new module, write go.mod |
go mod tidy |
Add missing requirements, remove unused ones |
go get pkg@version |
Add/upgrade a dependency |
go install pkg@version |
Build and install a binary into $GOPATH/bin |
go doc pkg.Symbol |
Read documentation without leaving the terminal |
2.2 Modules, not GOPATH
Pre-2019 Go required your code to live inside $GOPATH/src. Modules
(go.mod) decoupled that: any directory can be a module root. go.mod
pins your module's own import path and its dependencies' versions;
go.sum pins their cryptographic hashes so a build is reproducible even if
a dependency's tag is force-pushed upstream.
// go.mod
module github.com/kumaran/toolbelt
go 1.22
require (
github.com/spf13/cobra v1.8.0
)
2.3 Cross-compilation, usually simple for pure-Go code
Go's compiler targets are selected with two environment variables, and pure-Go programs usually do not need a separate compiler toolchain per target. If your build uses cgo, native libraries, or OS-specific files, you may need a matching C cross-compiler and target libraries.
GOOS=linux GOARCH=amd64 go build -o toolbelt-linux-amd64 .
GOOS=darwin GOARCH=arm64 go build -o toolbelt-mac-arm64 .
GOOS=windows GOARCH=amd64 go build -o toolbelt.exe .
2.4 Real-world example
A pure-Go CLI you build on your Apple Silicon laptop, tested with
go test ./..., can often be cross-compiled into a Linux amd64 binary and
dropped into a small container image with no language runtime dependency —
no python3, no node_modules, no JVM. This deployment story is one
reason so much infrastructure tooling (Docker, Kubernetes, Terraform,
Prometheus) is written in Go.