The go run and go build Commands
Using go run
'go run' compiles your code to a temporary location and runs it in a single command, then discards the binary. It's the fastest feedback loop for development because you never have to think about the intermediate executable file.
Example: Using go run
go run main.go
⚠️ Run this command in your terminal.
Using go build
'go build' compiles your program and writes a real executable file to the current directory, named after the module or the source file by default. This binary is a complete, self-contained program -- it embeds the Go runtime, so the machine running it does not need Go installed.
Note: On Windows the produced file automatically gets a .exe extension.
Example: Using go build
go build main.go
⚠️ Run this command in your terminal.
Naming the Output with -o
The -o flag lets you choose exactly where the compiled binary goes and what it's named, which is useful in build scripts and CI pipelines where a predictable filename matters.
Example: Naming the Output with -o
go build -o myapp main.go
⚠️ Run this command in your terminal.
Running the Compiled Binary
Once built, you execute the binary directly like any other program on your system. This two-step build-then-run workflow is what you'd use for anything meant to be deployed or distributed, as opposed to 'go run' which is meant purely for local iteration.
Note: Prefixing with ./ tells the shell to run the file from the current directory rather than searching PATH.
Example: Running the Compiled Binary
./myapp
⚠️ Run this command in your terminal.
- Using 'go run' in production deployment scripts instead of building a binary once with 'go build' and running that.
- Expecting 'go build' to execute the program -- it only compiles; you must run the resulting binary yourself.
- Not realizing 'go build' output binary defaults to the package/module name, leading to confusion about which file was produced.
- 'go run file.go' compiles and immediately executes a program without leaving a binary behind.
- 'go build' compiles the program into a standalone executable file on disk.
- 'go build -o name' lets you control the output binary's name.
- Built binaries need no external Go installation to run on a compatible OS/architecture.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: