Go Build: From Source Code to Executable
`go build` is your factory for turning Go source into a runnable program. It compiles your packages and their dependencies into a single executable. Use it to create a binary for deployment, but don't confuse it with `go install` which puts the file in your.
WHY IT EXISTS Go was designed for simplicity and speed, including the development workflow. go build exists to provide a single, standardized command to transform source code into a distributable, executable binary, automating the complex process of dependency resolution, compilation, and linking that previously required custom scripts or Makefiles.
THE MENTAL MODEL go build is like a self-contained factory. You give it the blueprint (your .go source files), and it gathers all the raw materials (your code and its dependencies from go.mod), assembles them, and produces a finished product (a single executable file) at the factory door (your current directory). It doesn't put the product on a delivery truck (go install) or just test the assembly line (go run).
HOW IT WORKS When you run go build, the Go toolchain analyzes the package in the current directory. It reads your go.mod file to identify and fetch all required dependencies. It then compiles your source files and the source files of all dependencies, linking them together into a single, statically-linked executable. The result is a file, typically named after the directory it was built in, that can run on the target operating system and architecture without needing Go or any external libraries installed. The build process is heavily cached, making subsequent builds much faster.
WHEN TO USE IT Use go build when you need to create a distributable artifact. This is the standard command for CI/CD pipelines, for building binaries to copy into Docker images, or for compiling a command-line tool that you want to place in a specific directory manually.
WHEN NOT TO USE IT For quick, temporary execution without creating a permanent binary, use go run. It compiles and runs in one step. To compile a tool and install it for system-wide use (placing it in your $GOBIN directory, which should be in your PATH), use go install.
ONE CANONICAL EXAMPLE Imagine a project in a directory named my-app with a main.go file inside. Running go build from within the my-app directory will produce an executable file named my-app (or my-app.exe on Windows) right in that same directory. You can then run ./my-app to execute it. To cross-compile for a different platform, like Linux from a Mac, you can use environment variables: GOOS=linux GOARCH=amd64 go build.
Read the original → pkg.go.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.