Building Go Programs
Start with Building Go Programs
Use go build to produce an executable that you can run again without recompiling the source each time.
What you’ll learn
- Compare go run with go build.
- Produce and execute a local binary.
- Understand why changing source does not update an old binary.
Understand the idea
Inside an executable module, go build compiles the main package and writes an executable file. Name the output explicitly with go build -o app . (on Windows use a filename such as app.exe). Then run the built file using the shell.
go run is convenient for development; go build creates an artifact you can distribute for a compatible operating system and architecture. A Go executable is not automatically compatible with every platform.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Build and execute
go build -o calculator .
./calculatorOn Windows, build with go build -o calculator.exe . and run .\calculator.exe in PowerShell.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
total := 12 + 8
fmt.Println("Total:", total)
}
Output
Total: 20Trace what the program does
The compiler checks the program and embeds the compiled instructions in an executable. Running that file starts main() and prints the same output as the development command.
Avoid common mistakes
go buildandgo runserve different purposes; the former does not automatically execute its artifact.- Do not assume the built binary has the same name or extension on every operating system.
Try it yourself
Build the example using go build -o calculator ., run the resulting executable, then modify the source and observe that the old binary stays unchanged until rebuilt.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Building Go Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.