Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 147 ยท Getting Started

How Go Works: Compiling and Running

Understand how Go turns source code into a fast static binary - go run vs go build vs go install, cross-compiling, the runtime, the scheduler and garbage collector.

Python and JavaScript read your source and run it through an interpreter. Go works differently: a compiler translates your whole program into machine code before it runs, and the result is an ordinary executable file. That is why Go programs start instantly, run fast and can be copied to another machine as a single file.

This lesson explains what happens between your .go file and a running program: the go command, the difference between go run, go build and go install, cross-compiling for other systems, and the small runtime that gets compiled into every Go program. You will also see what a runnable program must look like (package main and func main).

The shape of a runnable program

Every program you run in this course has the same skeleton. Press Run to see it work, and then we will take it apart:

Go The smallest complete program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

  • package main marks the file as an executable program. Any other package name makes a library that other code imports. Libraries have no entry point.
  • func main() is the entry point. It takes no arguments and returns nothing. When main returns, the program ends, even if other goroutines are still running. (Command-line arguments come from os.Args and the exit code from os.Exit; you will use both later.)
  • func init() is optional. A package can have one or more init functions, and Go runs them automatically after the package's variables are initialized and before main starts. They are handy for one-time setup, but explicit setup code called from main is usually easier to follow and to test.

If you forget main, the compiler says so. This example fails on purpose:

Go No main function (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You get this error (the first word is an internal symbol name, so it looks odd):

TEXT
runtime.main_mainยทf: function main is undeclared in the main package

If you name the package something other than main, the code compiles as a library, but go run refuses to run it because there is nothing to start.

From source to program

The go command does the work. These commands run in a terminal on your computer, so the blocks below are read-only: they show what you would type and see.

Terminal
# Compile and run immediately; the executable is thrown away
go run main.go

# Compile and keep the executable in the current folder
go build -o hello main.go
./hello

# Compile and install into $GOPATH/bin (or $GOBIN)
go install ./...

Our Run button works like go run: it compiles your file, runs the result and shows the output.

Command What it does Typical use
go run Builds in a temporary folder, runs the program, deletes the binary Trying things out
go build Builds and writes the executable into the current directory (or -o name) Making a program you ship
go install Builds and copies the executable into the install folder (GOBIN) Installing tools you want on your PATH

When you point go build at a package that has no main, it only checks that the code compiles and throws the result away. That makes it a quick way to find compile errors in a library.

Why builds are so fast

Go compiles each package once and caches the result. The language also forbids import cycles and unused imports, so the compiler never has to read huge headers over and over the way a C++ compiler does. A small program builds in well under a second, and a large one in seconds, which is why go run feels almost like running a script.

One file, no dependencies

A Go build produces a statically linked executable. Everything the program needs, including the standard library code you used and the runtime, is inside the file. There is no JVM to install and no node_modules to copy. Deploying a Go service can be as simple as uploading one file.

Our server builds programs with CGO_ENABLED=0, which means "do not use C code", and that is also the usual setting for portable Go binaries. The topic of calling C from Go is covered in unsafe and cgo.

Cross-compiling

Because the compiler is written in Go and the standard library is plain Go, one machine can build programs for many systems. You choose the target with two environment variables, GOOS (operating system) and GOARCH (processor family):

Terminal
# On any machine, build a Linux program for a 64-bit x86 server
GOOS=linux GOARCH=amd64 go build -o myapp-linux main.go

# Build for Windows
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go

# Build for an Apple Silicon Mac
GOOS=darwin GOARCH=arm64 go build -o myapp-mac main.go

# See every supported combination
go tool dist list

A program can also ask which system it was built for:

Go Asking the runtime about the build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

On our server this prints the Go version we compile with and linux amd64. On your laptop the last lines will show your own system.

Never rely on runtime.NumCPU() or runtime.GOMAXPROCS(0) for a "result" in tutorials or tests. They depend on the machine, and our sandbox deliberately has one CPU.

What is in the runtime?

Go has no virtual machine, but every program carries a small runtime written mostly in Go. It provides three important services:

  1. The scheduler runs goroutines (Go's lightweight threads) on a small pool of operating system threads. You can have hundreds of thousands of goroutines, because each starts with a stack of only a few kilobytes that grows as needed. See Scheduler Internals later in the course.
  2. The garbage collector finds memory your program no longer uses and frees it, concurrently with your code. You never call free. Garbage Collection explains how it works and how to tune it.
  3. Stack and heap management, bounds checks and the machinery behind maps, slices, channels and panics.

You can watch the collector work. The program below allocates garbage, forces a collection and reads the runtime's statistics:

Go Watching the garbage collector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You normally never call runtime.GC() yourself. The runtime decides when to collect. It is used here only to make the demonstration repeatable.

A program that outlives main?

When main returns, the whole program exits immediately, and any goroutines still running are cut off. This surprises many newcomers. The next example starts a goroutine, but main ends before it prints anything:

Go main ends, goroutine is dropped

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You will almost always see only main is done. It is not guaranteed, because goroutine scheduling is not under your control, but the goroutine rarely gets a chance to run before the program exits. Making main wait for goroutines properly is the topic of Goroutines and The sync Package.

Installing Go and running it locally

To use Go on your own computer, download the installer for your system from the official site, go.dev/dl, run it, and then open a new terminal:

Terminal
go version
# go version go1.27.3 linux/amd64   (yours will show your system)

Create a folder, save the hello-world program in main.go, and run go run main.go. For anything bigger than one file, you will want a module (a folder with a go.mod file), created with go mod init. Modules explains that in detail. Until then, our editor handles it for you.

If you only want to experiment, the official Go Playground at go.dev/play runs a single file in the browser, much like our editor does. It is also the easiest way to share a small snippet with someone.

The go command family

go is a toolbox, not just a compiler. The subcommands you will meet most often:

Command Purpose
go run, go build, go install Compile and run
go fmt Format source code
go vet Find suspicious code the compiler allows
go test Run tests and benchmarks
go mod Create and update modules
go get Add or upgrade a dependency
go doc Read documentation in the terminal
go env Show build settings

The go Command and Basic Tooling goes through the everyday ones with examples.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when func main returns?

    main returning ends the whole process. Other goroutines are stopped without finishing. Waiting for them takes a WaitGroup, a channel or similar.
  2. 2. Which command compiles your program and leaves an executable file in the current folder?

    go build writes the executable. go run compiles into a temporary folder and deletes it afterward, go vet only analyzes code, and go env prints settings.
  3. 3. How do you build a Windows executable from a Linux machine?

    Go cross-compiles by setting the GOOS and GOARCH environment variables. No extra tools are needed for pure Go code.
  4. 4. What is true about the package name main?

    Only package main produces a runnable program. Any other name builds a library without an entry point.
  5. 5. When does init() run?

    Go calls every init function automatically once per package, before main runs.

Summary

  • Go compiles the whole program to machine code ahead of time, so it starts fast and needs no interpreter.
  • A runnable program is package main with func main(). init() functions run automatically before main.
  • go run compiles and runs, go build leaves an executable, and go install puts it on your PATH.
  • Executables are static: copy one file to deploy. Set GOOS and GOARCH to cross-compile.
  • The runtime provides the goroutine scheduler and the garbage collector, and it is compiled into every program.
  • When main returns, the program ends, even if goroutines are still running.

Next: Go Syntax covers the rules of how Go code is written, from semicolons to exported names.