← Back to Go Course | Chapter 1: Setup & Basics | Lesson 4 of 7

The go run and go build Commands

'go run' is like test-driving a program once, while 'go build' bakes it into a real, saveable file you can hand to someone else.

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

bash
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

bash
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

bash
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

bash
./myapp

⚠️ Run this command in your terminal.

Common Mistakes
  1. Using 'go run' in production deployment scripts instead of building a binary once with 'go build' and running that.
  2. Expecting 'go build' to execute the program -- it only compiles; you must run the resulting binary yourself.
  3. Not realizing 'go build' output binary defaults to the package/module name, leading to confusion about which file was produced.
Chapter Summary
  • '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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.