Essential commands
Context
Section titled “Context”The go command is the primary interface to the Go toolchain. Here are the most important subcommands used daily.
Subcommands in detail
Section titled “Subcommands in detail”go run
Section titled “go run”Compiles and runs a Go program in one step. The compiled binary is placed in a temporary directory and deleted after execution.
go run main.goYou can pass arguments to the program after a -- separator:
go run main.go -- arg1 arg2go build
Section titled “go build”Compiles the current package and its dependencies. For a main package, it produces an executable binary. For a non‑main package, it compiles and discards the result (useful for checking errors).
# Build executable (name = directory name)go build
# Build with custom output namego build -o myapp
# Build for a different operating systemGOOS=windows GOARCH=amd64 go buildgo test
Section titled “go test”Runs tests defined in *_test.go files. It discovers functions named TestXxx(t *testing.T) and runs them.
# Run all tests in current directorygo test
# Verbose outputgo test -v
# Run specific test functiongo test -run=TestAdd
# Run tests with coveragego test -cover
# Run benchmarksgo test -bench=.go fmt
Section titled “go fmt”Formats Go source files according to the official style (no tabs, consistent indentation). This command rewrites files in place. It is safe to run on any Go code.
# Format current directorygo fmt
# Format all packages in the modulego fmt ./...go vet
Section titled “go vet”Reports suspicious constructs that are likely bugs, such as unreachable code, incorrect format strings, or race conditions (when run with -race). It does not produce false positives in most cases.
go vetgo vet ./...go mod tidy
Section titled “go mod tidy”Cleans up the go.mod and go.sum files by adding missing requirements and removing unused ones. Always run this before committing changes to a module.
go mod tidyExample
Section titled “Example”Compile and run a simple program.
Code example
Section titled “Code example”go run main.goOutput
Section titled “Output”Hello, Go!