LESSON · 1 OF 20

Building a binary with go build

Building a binary with go build

go run compiles your code to a temporary binary, runs it, and throws the binary away. That is perfect while you iterate. When you want a real binary you can keep and ship, you use go build.

Run go build from inside a module directory and it compiles your package into an executable in the current folder:

text
go build

For a main package the binary is named after the module (or the folder). If your module is example.com/greet, you get a file called greet, and you run it directly:

text
./greet

No Go toolchain is needed to run it. A compiled Go binary is a single self-contained file, which is a big part of why Go is popular for CLIs and services: you build once and copy the binary to the target.

The shape to memorise

  • go build compiles a keepable binary named after the module into the current directory.
  • Run it with ./name, and no Go toolchain is needed on the target.
Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute