Skip to content
LumenaryAcademy
Foundations 45 min

Getting started with Go

Why Go was made, how to install it, and your first programs with modules, go run and fmt.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

A language for building servers, and for the people who maintain them

In 2007, three engineers at Google (Robert Griesemer, Rob Pike and Ken Thompson) were frustrated. Google's servers were written mostly in C++ and Java. Building a large C++ program could take long enough to go for coffee; the languages had grown complicated enough that each team used a different subset; and writing programs that did many things at once, the everyday work of a network server, was hard to get right with threads and locks.

They set out to design a language that would compile very quickly, read clearly even to someone new to the codebase, make concurrent programs natural to write, and stay small enough to hold in your head. The result was Go. Its specification is short enough to read in an afternoon. Its features were chosen as much for what they leave out as for what they add: no inheritance, no exceptions, few ways to write the same thing, and (until 2022) no generics.

Go also manages memory for you with a garbage collector, so it is safer and simpler than C or C++, while compiling to native machine code that starts instantly and runs fast. The trade-off is less control over memory layout and timing than a systems language like C or Rust offers, which matters for an operating-system kernel and rarely for a web service.

This combination made Go the language of cloud infrastructure. Docker, Kubernetes, Terraform, Prometheus, etcd and many other tools that run today's data centres are written in it, and it is widely used for web back ends, command-line tools and networking software.

History & global context

From 2007 to today

Go was announced as an open-source project on 10 November 2009. Go 1.0 followed in March 2012, together with a promise that has shaped the language ever since: programs written for Go 1 would keep compiling and running, unchanged, with every later Go 1.x release. Over a decade later the promise has held, which is a large part of why companies trust Go for long-lived systems.

Go's ancestry shows in its design. The expression syntax and the compile-to-machine-code model come from C, which Thompson had helped create. Declarations that read "name, then type" and the package system owe much to Pascal and Niklaus Wirth's Oberon, with which Griesemer had worked during his doctoral studies at ETH Zürich. And goroutines and channels descend from Tony Hoare's 1978 idea of communicating sequential processes (CSP), which Pike had explored in earlier languages of his own, Newsqueak and Limbo.

Within that promise the language has grown carefully. Modules, Go's system for versioned dependencies, arrived in 2018 and became the default in 2021. Generics (type parameters) arrived in Go 1.18 in March 2022, after more than a decade of design discussion. Go 1.22 (2024) gave each loop iteration its own variables, fixing a long-standing trap, and Go 1.23 let for range loop over iterator functions. Go 1.26 allowed new to take an initial value, and Go 1.27, released in August 2026 and used throughout this course, lets methods have their own type parameters.

New versions appear twice a year, in February and August. Each release is supported until two newer ones have appeared. The language's mascot, the gopher, was drawn by Renée French, and Go programmers often call themselves gophers.

DefinitionsH

Installing Go, and the go command

Download an installer from go.dev/dl and follow the instructions on the installation page. Everything comes as one program, go, with subcommands: it compiles, runs, tests, formats, fetches dependencies, documents and profiles. Check your installation:

bash
go version

If you'd rather not install yet, the Go Playground runs programs in the browser; every complete program in this course works there.

Definition— package

Every Go source file begins with package name. A package is a directory of .go files that are compiled together and share one namespace. A program's entry point is the function main in package main. Other packages are brought in with import; names that start with a capital letter are exported (visible outside the package), and all others are private to it.

Definition— module

A module is a collection of packages released together, described by a go.mod file at its root that gives the module's path and the Go version it needs, and lists its dependencies. Since Go 1.16, modules are the normal way to organise all Go code.

Create your first module:

bash
mkdir hello && cd hello
go mod init example.com/hello

This writes a two-line go.mod:

text
module example.com/hello

go 1.27.4

The module path looks like a web address because, for published code, it usually is one (github.com/someone/project); for a private experiment any name will do. Put a program in main.go, then:

CommandWhat it does
go run .compiles the package in the current directory into a temporary executable and runs it
go buildcompiles it into an executable named after the module (hello)
go vet ./...checks for suspicious code that compiles but is probably wrong
gofmt -w . or go fmt ./...rewrites files in the one standard Go layout

./... means "this directory and everything below it". Builds are fast: the compiler was designed so that each package needs to read only the compiled form of the packages it imports.

Worked examplesH

Your first programs

go
package main

import "fmt"

func main() {
	fmt.Println("Hello, world!")
	fmt.Println("Sawubona, mhlaba! Xin chào thế giới! こんにちは世界!")
}
text
Hello, world!
Sawubona, mhlaba! Xin chào thế giới! こんにちは世界!

Line by line: the file belongs to package main; it imports the standard library's fmt package (short for "format"); and func main() is where execution starts. fmt.Println prints its arguments followed by a newline. Println starts with a capital letter because it is exported from fmt. Go source files are UTF-8, so text in isiZulu, Vietnamese and Japanese prints as written. There are no semicolons: the compiler inserts them at the ends of lines for you, which is also why an opening brace must stay on the same line as the func or if before it.

Formatting values

fmt.Printf takes a format string with verbs that start with %:

go
package main

import "fmt"

type city struct {
	Name       string
	Population int
}

func main() {
	language, year := "Go", 2009
	ratio := 2.0 / 3.0
	c := city{"Montevideo", 1_300_000}

	fmt.Println(language, "was announced in", year)
	fmt.Printf("%s turned %d in %d\n", language, 2026-year, 2026)
	fmt.Printf("two thirds is about %.3f\n", ratio)
	fmt.Printf("[%6s] [%-6s] [%06d]\n", "right", "left", 42)
	fmt.Printf("%v | %+v | %T\n", c, c, c)
	fmt.Printf("%q %x %t %c\n", "quoted", 255, true, 'λ')
	s := fmt.Sprintf("%d%%", 75) // Sprintf returns the string instead of printing it
	fmt.Println(s, len(s))
}
text
Go was announced in 2009
Go turned 17 in 2026
two thirds is about 0.667
[ right] [left  ] [000042]
{Montevideo 1300000} | {Name:Montevideo Population:1300000} | main.city
"quoted" ff true λ
75% 3

The verbs you will use most:

VerbPrints
%vany value in its default format; %+v adds struct field names
%d, %s, %fan integer, a string, a floating-point number (%.3f: three decimals)
%qa string in double quotes, with escapes
%Tthe value's type
%x, %c, %thexadecimal, a character, a boolean
%%a literal percent sign

A number between % and the verb sets a minimum width (%6s), a minus sign left-aligns (%-6s) and a leading zero pads with zeros (%06d). Sprintf returns the formatted string, and Fprintf writes to any file or network connection. Printf does not add a newline, so format strings usually end in \n.

The program also previews two things later lessons explain: language, year := "Go", 2009 declares two variables at once with :=, and city is a struct, a type with named fields.

A program that computes something

go
package main

import (
	"fmt"
	"math"
)

// yearsToDouble returns how many whole years money takes to at least double
// at the given yearly interest rate, compounded once a year.
func yearsToDouble(ratePercent float64) int {
	balance := 1.0
	years := 0
	for balance < 2.0 {
		balance *= 1 + ratePercent/100
		years++
	}
	return years
}

func main() {
	fmt.Println("rate  exact  rule of 72")
	for _, rate := range []float64{2, 4, 6, 8, 12} {
		exact := math.Log(2) / math.Log(1+rate/100)
		fmt.Printf("%3.0f%%  %5.1f  %4.1f  (doubles in year %d)\n",
			rate, exact, 72/rate, yearsToDouble(rate))
	}
}
text
rate  exact  rule of 72
  2%   35.0  36.0  (doubles in year 36)
  4%   17.7  18.0  (doubles in year 18)
  6%   11.9  12.0  (doubles in year 12)
  8%    9.0   9.0  (doubles in year 10)
 12%    6.1   6.0  (doubles in year 7)

A function, a loop and a slice of numbers: lesson 2 and lesson 3 cover each properly. Notice the shape of the function signature, func yearsToDouble(ratePercent float64) int, where types come after names, and for balance < 2.0, Go's only loop keyword used like a while. The table compares the exact doubling time with the "rule of 72" that bankers use as a mental shortcut.

ExplanationH

How Go programs are built, and a strict compiler

Go compiles ahead of time to a single native executable that contains your code, the parts of the standard library it uses, and the Go runtime: the garbage collector and the scheduler that runs goroutines (lesson 8). By default the executable has no external dependencies, so deploying a Go service often means copying one file onto a server or into a minimal container image. Cross-compiling is one environment variable away: GOOS=windows GOARCH=amd64 go build on a Linux laptop produces a Windows program.

The compiler is strict in one way that surprises newcomers. An unused variable or an unused import is a compile error, not a warning:

go
package main

import (
	"fmt"
	"os"
)

func main() {
	greeting := "Habari"
	name := "Juma"
	fmt.Println(greeting + ", world")
}
text
# command-line-arguments
./main.go:5:2: "os" imported and not used
./main.go:10:2: declared and not used: name

The reasoning is that unused code is usually a mistake (a typo, a forgotten step) and that warnings get ignored. In practice your editor fixes imports for you as you save: the gopls language server (in VS Code's Go extension, GoLand, Neovim and others) adds and removes imports and formats the file automatically. During experiments, assign a value to the blank identifier, _ = name, to keep the compiler quiet for a moment.

The other habit you will see in every Go codebase is gofmt. There is exactly one accepted layout for Go code (tabs for indentation, a particular spacing and alignment), and the tool applies it. Nobody argues about brace placement in Go code review, and reading someone else's code feels like reading your own.

ExplanationH

The Go way of working

Every language has a culture, and Go's is unusually consistent. Knowing it early will make the rest of the course, and other people's Go code, easier to read.

Plain code over clever code. Go programmers prefer a few extra lines that anyone can follow to a compact trick that needs a comment. Loops are written out; there is no ternary ?: operator; errors are checked where they happen. Code reviews in Go teams often ask "could this be simpler?" before anything else.

The standard library first. Go ships with a large, carefully designed standard library: HTTP clients and servers, JSON, cryptography, compression, testing, templates, structured logging. Many production services depend on only a handful of outside modules. When you need something, look at pkg.go.dev/std before searching for a third-party package.

Documentation from the command line. go doc fmt.Printf prints the documentation for a function in your terminal, and go doc -all strings a whole package. Documentation comments are plain sentences that start with the name they describe ("Printf formats according to a format specifier..."), and pkg.go.dev renders them for every public module.

Small names in small scopes. Go style uses short names for short-lived variables (i, n, err, r for a reader) and longer, descriptive names for things that are visible across a package. Package names are short, lower-case single words (strings, http, json), and exported names are read together with them, so the standard library has http.Server, not http.HTTPServer.

Tools enforce the rules, so people don't have to. gofmt fixes layout, go vet flags suspicious constructs (a Printf verb that doesn't match its argument, an unreachable line), and the compiler rejects unused code. The time saved in review goes into discussing design.

Rob Pike gathered many of these attitudes into short sayings, the Go Proverbs, which are worth a look once you have written some Go. And when a design choice seems odd, the Go FAQ usually explains the reasoning in the designers' own words.

Common misconceptionsH

Common misconceptions

Misconception

"Go is an interpreted scripting language, because of go run." go run compiles the program to a temporary executable and runs it; it is a convenience. Go is compiled to native machine code, like C or Rust.

Misconception

"A garbage collector makes Go too slow for serious systems." Go's collector runs mostly concurrently with your program and is tuned for short pauses; Go 1.26 made a newer collector design, nicknamed Green Tea, the default. For network services the collector's cost is usually small next to the time spent waiting on networks and disks. It matters for hard real-time systems and some latency-critical niches, which is the honest limit.

Misconception

"Simple means Go is a beginner's language." Simplicity was a design goal for large teams and long-lived code, not a ceiling. Some of the most demanding infrastructure software in the world is written in Go precisely because a new engineer can read it.

Misconception

"Println and Print differ only by the newline." Println always puts spaces between its operands; Print adds a space only between two operands when neither is a string. The exercises test this.

Exercises

Exercises

1. Getting started with Go

CoreComputational

What does this line print?

fmt.Print("a", "b", 1, 2, "c\n")

2. Getting started with Go

CoreComputational

What does this print?

fmt.Printf("%d-%s|%v|%x\n", 7, "seven", []int{7}, 26)

3. Getting started with Go

Warm-upHuman

A program imports "os" but never uses it. What happens when you run go build?

Choose one

4. Getting started with Go

CoreHuman

Package geo declares func Distance(...), func haversine(...) and var Earth. Which of them can another package use as geo.Name?

Choose one

5. Getting started with Go

Warm-upHuman

Which statements about the go command are true? Choose all that apply.

Choose all that apply

6. Getting started with Go

Warm-upHuman

Go 1.0 shipped in 2012 with the Go 1 compatibility promise. In which year did Go gain generics (type parameters), with Go 1.18?

Further reading and resources