Knaph

The course as a book

Introduction to Go

A hands-on tour of Go for programmers coming from other languages — syntax, types, concurrency, and the standard library, taught by building small working programs.

First Contact

Installing Go and Hello, World

You're going to write and run a real Go program in the next few minutes. Not a REPL snippet — a file, compiled and executed by the same toolchain you'd use to ship production code.

Install Go

Go ships as a single toolchain — no separate package manager to install first, no virtual environment to set up. Grab it from go.dev/dl for your OS, or use a package manager:

# macOS
brew install go
 
# Ubuntu/Debian
sudo apt install golang-go
Shell

Confirm it worked:

go version
Shell

You should see something like go version go1.23.0 darwin/arm64.

Write the smallest Go program

Create a file called main.go:

package main
 
import "fmt"
 
func main() {
	fmt.Println("Hello, Go")
}
Go

Every executable Go program has exactly this shape, and each line is doing something specific:

  • package main — this file belongs to the main package, which is what makes it a program you can run, not just a library other code imports.
  • import "fmt" — pulls in the standard library's formatting/printing package. Go's standard library is large and genuinely good; you'll reach for it constantly.
  • func main() — the entry point. When you run the program, this is where execution starts. There's no ambiguity about "what runs first" the way there can be in a script with top-level statements — in Go, it's always main().

Run it

go run main.go
Shell

You should see:

Hello, Go

go run compiles the file to a temporary binary and executes it in one step — the fast loop for trying things out. When you want an actual binary you can hand to someone else:

go build main.go
./main
Shell

go build produces a single, statically linked executable — no runtime to install on the machine that runs it, no node_modules, no interpreter version to match. That's a large part of why Go is a common choice for command-line tools and small services: you build once and ship a file.

A note if you're coming from Python

Two habits to unlearn early:

  • Every file that's part of a build must compile. There's no equivalent of running one function in a file that has an unrelated syntax error somewhere else — Go compiles the whole package before anything runs.
  • Unused imports and unused local variables are compile errors, not warnings. Import fmt and then never call anything from it, and go run refuses to run at all. This feels strict at first; in practice it means a Go codebase rarely accumulates the slow drift of dead imports and copy-pasted-then-abandoned variables that's easy to ignore in a more permissive language.

Lesson page →

Variables

Go is statically typed — every variable has a fixed type, checked at compile time, not at runtime. Coming from Python, this is the biggest day-to-day difference you'll feel, so let's get comfortable with it immediately.

Declaring variables

The explicit form:

var age int = 34
var name string = "Haleh"
Go

You'll rarely write it that way inside a function, though. Go infers the type from the value, so this is equivalent and far more common:

age := 34
name := "Haleh"
Go

:= declares and initializes in one step. It only works for a brand-new variable inside a function — you can't use it to declare package-level variables, and you can't use it to reassign an existing one (use plain = for that).

age := 34
age = 35   // reassignment, no :=
Go

Try mixing types where Go doesn't expect them:

age := 34
age = "thirty-five"
Go
./main.go:6:7: cannot use "thirty-five" (untyped string constant) as int value in assignment

That's the compiler catching a bug that, in Python, wouldn't surface until the line actually ran — possibly in production, possibly much later than the line that caused it.

Naming and exporting

Go doesn't have public/private keywords. Instead, capitalization controls visibility:

var ExportedName = "visible outside this package"
var unexportedName = "only visible inside this package"
Go

An identifier starting with an uppercase letter is exported (importable by other packages); lowercase means package-private. You'll see this rule everywhere once you know it's there — it's why standard library functions like fmt.Println and strings.Split are capitalized. This rule isn't just for variables — it applies the same way to functions, types, and constants, which you'll meet next.

Lesson page →

Basic Types

The basic types

The ones you'll use constantly:

var i int        // platform-sized integer (64-bit on virtually everything today)
var f float64     // 64-bit floating point
var b bool        // true or false
var s string      // UTF-8 text, immutable
Go

There are also sized integer types (int8, int32, uint64, ...) for when the exact width matters — packing bytes for a network protocol, say — but reach for plain int by default.

A variable declared with var and no value gets its type's zero value, not null/None/undefined:

var count int     // 0
var label string  // ""
var ready bool    // false
Go

Every type has exactly one zero value:

TypeZero value
int, int8…int64, uint…uint64, byte, rune0
float32, float640
complex64, complex1280+0i
boolfalse
string"" (empty, not nil)
pointer (*T)nil
slice ([]T)nil (behaves as an empty, length-0 slice)
map (map[K]V)nil (readable as empty; writing to it panics)
channel (chan T)nil
functionnil
interfacenil
structeach field set to its own zero value
array ([N]T)every element set to T's zero value

This is deliberate: Go doesn't have a universal nil-for-anything the way Python has None for every variable. Only a handful of types (pointers, slices, maps, interfaces, channels, functions) can be nil; an int or string always has a real, usable zero value, so there's no "forgot to initialize it, now it's null and everything downstream throws" class of bug for these types.

Lesson page →

Constants

Constants

const is for values that are fixed at compile time and can never be reassigned:

const Pi = 3.14159
const MaxRetries = 3
Go

Attempting MaxRetries = 4 later is a compile error, not a lint warning. Use const for the "this should never change" values in your program — timeouts, limits, magic numbers you want named — the same instinct as Python's SCREAMING_SNAKE_CASE module constants, except Go actually enforces it.

Lesson page →

Tooling

Adding Go to Your PATH

Your shell finds a command by walking the directories in $PATH. Two Go-related directories need to be on it, for two different reasons.

The toolchain itself. If go version worked in the last module, this is already done — your package manager handled it. If you unpacked the tarball from go.dev/dl by hand, it lives in /usr/local/go and nothing has told your shell yet.

Binaries that go install produces. This is the one that bites. go install compiles a command-line tool and puts it in $GOPATH/bin — ~/go/bin unless you've changed it. If that's not on your PATH, the install reports success and the very next line says command not found. You'll install two tools in this module, so fix it now.

go env GOROOT   # where the toolchain itself lives
go env GOPATH   # the root `go install` puts binaries under (default: ~/go)
Shell

Add both to your shell's startup file — ~/.zshrc on macOS, ~/.bashrc on most Linux setups:

export PATH="$PATH:/usr/local/go/bin"   # only needed for a tarball install
export PATH="$PATH:$HOME/go/bin"        # where `go install` puts binaries
Shell

Open a new terminal (or source ~/.zshrc), then confirm with which go.

Coming from Python, go install is roughly pipx install: it puts a standalone tool on your PATH globally, not into a per-project environment. ~/go/bin is Go's ~/.local/bin.

Lesson page →

gofmt

Go shipped with a formatter on day one and the whole ecosystem adopted it. That means no per-project style config to negotiate, no black vs. autopep8 decision, and no tabs-versus-spaces thread in code review. (It's tabs. It's settled. It isn't configurable.) Every Go file you'll ever read is laid out the same way, so your eye stops spending effort on it.

Two commands, one engine:

  • gofmt is the formatter. Give it files or directories; by default it prints the result and changes nothing.
  • go fmt wraps it as gofmt -l -w over packages, so it needs a go.mod. You don't have one yet — until then, name files directly.
gofmt -d main.go    # show what it would change, as a diff
gofmt -w main.go    # rewrite the file in place
gofmt -l .          # list files that need formatting - the CI check
Shell

The file below compiles and runs exactly as written. Go is insensitive to this whitespace, which is precisely why it can be normalized mechanically:

Before gofmt
package main
 
import "fmt"
 
func main(){
x:=3
y := 4
if x<y {
fmt.Println("x is smaller" )
}
}
Go
After gofmt
package main
 
import "fmt"
 
func main() {
	x := 3
	y := 4
	if x < y {
		fmt.Println("x is smaller")
	}
}
Go

Indentation by tabs, one space on each side of := and <, ){ opened up to ) {, and the stray space before ) dropped. All of it is layout — gofmt never changes what your program does.

One useful side effect: gofmt has to parse your file, so it refuses to touch one with a syntax error. If gofmt won't format it, it won't compile either.

Lesson page →

goimports

goimports does everything gofmt does, and then fixes your imports. Install it — this is what the PATH lesson was for:

go install golang.org/x/tools/cmd/goimports@latest
goimports -d main.go    # same flags as gofmt: -d, -w, -l
Shell

Three things it does that gofmt won't:

  1. Removes imports you aren't using. Not tidying — an unused import is a compile error in Go, so this is the difference between a file that builds and one that doesn't.
  2. Adds imports for packages you reference but never imported.
  3. Groups the standard library separately from everything else.

Here strings is imported but unused, and os is used but missing:

Before goimports
package main
 
import (
	"strings"
	"fmt"
)
 
func main() {
	fmt.Fprintln(os.Stdout, "hello")
}
Go
After goimports
package main
 
import (
	"fmt"
	"os"
)
 
func main() {
	fmt.Fprintln(os.Stdout, "hello")
}
Go

Plain gofmt on that same file sorts the two lines into "fmt", "strings" and stops. The unused import stays, os is still missing, and it still doesn't compile. Sorting is a style fix; adding and removing is a correctness fix.

The grouping rule shows up once you have an outside dependency:

Before goimports
import (
	"github.com/google/uuid"
	"fmt"
	"net/http"
)
Go
After goimports
import (
	"fmt"
	"net/http"
 
	"github.com/google/uuid"
)
Go

Standard library first, a blank line, then everything else. You'll see this shape in every Go codebase and never have to maintain it by hand.

goimports is a superset of gofmt, so it's the one to enable as format-on-save in your editor. One caveat: when a name is ambiguous — rand could be math/rand or crypto/rand — it has to guess, and occasionally guesses wrong.

Lesson page →

go vet

Go's compiler is stricter than most — an unused import or unused local variable is a hard error, not a warning — so a whole category of linting doesn't exist here. What's left is the interesting part: code that is perfectly valid Go and almost certainly not what you meant.

package main
 
import "fmt"
 
func main() {
	name := "Haleh"
	fmt.Printf("hello %d\n", name)
}
Go
go run main.go
Shell
hello %!d(string=Haleh)

It compiled, it ran, and it printed nonsense. The compiler had no grounds to object: Printf takes ...any, so passing a string is fine as far as the type system is concerned. The mismatch is between the contents of a string literal (%d) and an argument — a relationship only a tool that understands Printf can check.

That tool ships with Go:

go vet main.go
Shell
main.go:7:20: fmt.Printf format %d has arg name of wrong type string

A sample of what its analyzers cover:

  • format strings that don't match their arguments
  • struct tags that don't parse — a json:"name" typo'd as json"name" silently does nothing
  • unreachable code
  • a lock copied by value instead of by pointer

The list is deliberately short. Vet only reports what is almost certainly a mistake, never merely suspicious — false positives train you to ignore a tool, and an ignored tool is worse than none. That restraint earned it a privileged position: go test runs a subset of vet automatically, so the file above fails the test run without anyone asking for it.

Like go fmt, the ./... form needs a go.mod. Until you have one, name files directly.

Lesson page →

staticcheck

Vet's narrowness leaves a lot on the table. staticcheck is the other well-known Go analyzer: well over a hundred checks, still tuned hard against false positives, but willing to flag things vet considers out of scope.

go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...
Shell

Here's a bug vet misses entirely:

package main
 
import (
	"fmt"
	"strings"
)
 
func main() {
	name := "  Haleh  "
	strings.TrimSpace(name)
	fmt.Println("hello, " + name + "!")
}
Go
hello,   Haleh  !

go vet ./... reports nothing. staticcheck ./... reports:

main.go:10:2: TrimSpace doesn't have side effects and its return value is ignored (SA4017)

Go strings are immutable, so strings.TrimSpace hands you a new string rather than editing the one you passed in. Throw the return value away and the call accomplished nothing at all:

Before
name := "  Haleh  "
strings.TrimSpace(name)
fmt.Println("hello, " + name + "!")
Go
After
name := "  Haleh  "
name = strings.TrimSpace(name)
fmt.Println("hello, " + name + "!")
Go

Every finding carries a stable code, and its prefix tells you the kind: SA is a likely bug, S1 a simplification, ST a style convention. The code is what you cite to silence one deliberately — //lint:ignore SA4017 <reason> on the line above — and staticcheck requires that reason.

One piece of history, because you'll trip over it: if you find golint recommended in an old blog post or Stack Overflow answer, skip it. It was deprecated and frozen in 2021, and its own README now points at go vet and staticcheck instead.

Lesson page →

golangci-lint

golangci-lint isn't a linter. It's a runner that bundles over a hundred of them — vet and staticcheck included — loads and type-checks your code once, runs them all in parallel against that shared view, and caches the result. One fast command instead of three tools each re-parsing your project, which is why it's what most Go projects run in CI.

brew install golangci-lint   # macOS; released binaries are the documented install
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest
Shell

Out of the box, v2 enables five: errcheck, govet, ineffassign, staticcheck, and unused. This file compiles, runs, and go vet ./... finds nothing in it:

package main
 
import (
	"fmt"
	"strings"
)
 
func shout(s string) string {
	return strings.ToUpper(s)
}
 
func main() {
	name := strings.TrimSpace("  Dr. Haleh  ")
 
	greeting := "hello"
	greeting = "hello, " + name
 
	isDoctor := strings.HasPrefix(name, "Dr.")
	if isDoctor == true {
		greeting = "good day, " + name
	}
 
	fmt.Println(greeting)
}
Go
golangci-lint run ./...
Shell
main.go:15:2: ineffectual assignment to greeting (ineffassign)
main.go:19:5: S1002: should omit comparison to bool constant, can be simplified to isDoctor (staticcheck)
main.go:8:6: func shout is unused (unused)

Three findings from three different linters, each a fair complaint: an assignment overwritten before anything reads it, a comparison to true on a value that's already a bool, and a helper nobody calls. Notice each line names the linter that produced it — that's how you know what to configure or turn off.

Configuration goes in .golangci.yml at the repo root:

version: "2"
 
linters:
  enable:
    - errcheck
    - govet
    - ineffassign
    - staticcheck
    - unused
    - misspell
YAML

The version: "2" line is required — v2 changed the config format and a v1-era file won't load. Start near the defaults; enabling all hundred is a reliable way to end up ignoring the tool.

Some findings have a mechanical fix, and --fix applies them:

Before --fix
isDoctor := strings.HasPrefix(name, "Dr.")
if isDoctor == true {
	greeting = "good day, " + name
}
Go
After --fix
isDoctor := strings.HasPrefix(name, "Dr.")
if isDoctor {
	greeting = "good day, " + name
}
Go

It fixed that one and left the other two alone, which is correct — only you know whether an unused helper should be deleted or wired up.

So: run go vet always, since it's free and partly runs inside go test anyway. On a real project run golangci-lint run ./..., which includes both vet and staticcheck, and put that same command in CI — it exits non-zero when it finds anything. To silence a single finding, add //nolint:unused // kept for the CLI rewrite on the line, always with a reason.

Lesson page →

A Makefile for the Toolchain

You now have a tool for formatting, a tool for imports, and a checker for likely bugs — each with its own command and flags. Go projects put them behind make, so nobody has to remember any of it. Open the Makefile in almost any Go repository and you'll find the same handful of target names: build, fmt, vet, clean.

.DEFAULT_GOAL := build
 
.PHONY: tools
tools:
	go install golang.org/x/tools/cmd/goimports@latest
 
.PHONY: fmt
fmt:
	goimports -w .
 
.PHONY: vet
vet:
	go vet main.go
 
.PHONY: build
build: fmt vet
	go build main.go
 
.PHONY: clean
clean:
	rm -f main
Makefile

Run make with no arguments and it does the whole chain, because .DEFAULT_GOAL points at build and build lists fmt and vet as prerequisites — make runs those first:

goimports -w .
go vet main.go
go build main.go

If vet finds something, make stops there and never reaches the build:

goimports -w .
go vet main.go
main.go:7:20: fmt.Printf format %d has arg name of wrong type string
make: *** [vet] Error 1

That's the real value: one word, and a mistake can't slip past into a binary. Each target still works on its own — make fmt, make vet, make tools on a fresh machine.

Two pieces of Make worth naming:

  • .PHONY marks a target that isn't a file. Make normally treats a target as a filename and skips it when that file looks up to date, so without .PHONY your build target would quietly stop working the day a file named build appeared.
  • Every recipe line must start with a real tab, not spaces. Make rejects the file with missing separator otherwise, and editors convert tabs silently. This catches everyone exactly once.

These targets name main.go directly, because commands like go vet ./... need a go.mod and you don't have one yet. Once you do, the same targets grow to cover the whole project — and staticcheck and golangci-lint, which both need a module too, drop straight in beside vet.

Lesson page →

Control Flow and Functions

If

Go deliberately has fewer control-flow keywords than most languages. There's no while, no do-while, no ternary operator. Once you know why, it stops feeling like a missing feature and starts feeling like one less thing to decide between.

if

age := 20
 
if age >= 18 {
	fmt.Println("adult")
} else if age >= 13 {
	fmt.Println("teen")
} else {
	fmt.Println("child")
}
Go

Two things jump out coming from most other languages: no parentheses around the condition, and the braces are mandatory — you can't write a one-line if without them. Both are enforced by the compiler, not just a style guide, which means every Go codebase you read looks like this one.

if also accepts an initializer statement — a short statement that runs right before the condition is checked, scoped to just the if/else chain. It looks unfamiliar at first, so let's build up to it in pieces, using only what you already know: := and comparisons.

Here's the same code written two ways. First, as two separate lines:

x := 10
if x > 5 {
	fmt.Println("big:", x)
} else {
	fmt.Println("small:", x)
}
Go

Now with the initializer folded into the if, using a semicolon to separate the setup statement from the condition:

if x := 10; x > 5 {
	fmt.Println("big:", x)
} else {
	fmt.Println("small:", x)
}
Go

Read it as two statements glued together — x := 10 runs first, then x > 5 is checked as the condition, exactly like the two-line version above. The semicolon is the seam: everything before it is the initializer, everything after it is the condition.

Why fold it in at all? Scope. A variable declared in the initializer only exists inside the if/else if/else chain it belongs to — not in the rest of the function:

if x := 10; x > 5 {
	fmt.Println("big:", x)
}
fmt.Println(x) // compile error: undefined: x
Go

With the two-line version, x would still be sitting in the function's scope after the if block ends — available to be misused, or to collide with another variable named x later on.

This becomes genuinely useful once a statement can produce more than one value — which is exactly what you'll see in the upcoming Functions and Errors lessons later in this module, in patterns like:

if err := doSomething(); err != nil {
	return err
}
Go

Here err only needs to exist long enough to be checked, then it's gone — the next line down can declare its own err := ... with no conflict. You'll see this constantly once functions and errors are in play; for now, the thing to hold onto is just this: if can run a short setup statement right before its condition, and whatever that statement declares only lives inside that if/else chain.

No ternary operator

Python has x if cond else y; Go has nothing shorter than a full if/else. This is intentional — the language designers left it out on purpose to avoid the nested-ternary readability problem, and the idiomatic replacement is just to write the if:

status := "child"
if age >= 18 {
	status = "adult"
}
Go

It's a few more lines than a ternary. Once you've read enough Go, you'll find you stop missing it.

Lesson page →

For

for — Go's only loop

Go has one loop keyword, and it covers every case other languages split across for, while, and do-while.

The classic three-part form:

for i := 0; i < 5; i++ {
	fmt.Println(i)
}
Go

Drop the init and post clauses and it's a while loop:

n := 10
for n > 0 {
	fmt.Println(n)
	n--
}
Go

Drop the condition too and it loops forever, until something inside breaks out:

for {
	// runs until a break
}
Go

And for ... range iterates over slices, arrays, maps, and strings:

names := []string{"Ada", "Grace", "Haleh"}
for i, name := range names {
	fmt.Println(i, name)
}
Go

If you only need the value, discard the index with _ — Go requires you to explicitly acknowledge an unused loop variable, not just leave it dangling:

for _, name := range names {
	fmt.Println(name)
}
Go

Lesson page →

Switch

switch

Go's switch doesn't fall through by default — each case breaks automatically, which is the behavior most people actually want and forget to write in C-family languages:

switch dayNumber {
case 1, 7:
	fmt.Println("weekend")
case 2, 3, 4, 5, 6:
	fmt.Println("weekday")
default:
	fmt.Println("invalid")
}
Go

A switch with no expression at all reads like a cleaner if/else-if chain:

switch {
case age >= 18:
	fmt.Println("adult")
case age >= 13:
	fmt.Println("teen")
default:
	fmt.Println("child")
}
Go

Lesson page →

Functions

Basic functions

func add(a int, b int) int {
	return a + b
}
Go

Parameter and return types are explicit — no inference on a function signature the way there is on a local variable. When consecutive parameters share a type, you can write it once:

func add(a, b int) int {
	return a + b
}
Go

Multiple return values

This is the feature that shapes almost everything else about how Go code is written. A function can return more than one value, no tuple or object wrapper required:

func divide(a, b int) (int, int) {
	quotient := a / b
	remainder := a % b
	return quotient, remainder
}
 
q, r := divide(17, 5)
fmt.Println(q, r) // 3 2
Go

You can even name the return values in the signature, which both documents them and gives you a "naked return" shorthand:

func divide(a, b int) (quotient, remainder int) {
	quotient = a / b
	remainder = a % b
	return
}
Go

Variadic functions

A function can accept a variable number of arguments with ...:

func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}
 
sum(1, 2, 3)       // 6
sum(1, 2, 3, 4, 5) // 15
Go

Inside the function, nums is just a slice of int — you'll meet slices properly next module. fmt.Println itself is variadic, which is why you can pass it any number of arguments of any type.

Lesson page →

Errors

Why this matters: errors are just a second return value

Go has no try/except. There's a built-in error type — actually just an interface with one method, Error() string — and the convention is that any function that can fail returns one as its last value:

func divide(a, b int) (int, int, error) {
	if b == 0 {
		return 0, 0, fmt.Errorf("divide by zero: %d / %d", a, b)
	}
	return a / b, a % b, nil
}
Go

nil is what "no error" looks like — the zero value for the error interface. Calling code is expected to check it immediately, before touching the other return values:

q, r, err := divide(10, 0)
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println(q, r)
Go

You will write if err != nil { ... } an enormous number of times in Go code. It looks repetitive the first week and becomes close to invisible after that — your eye learns to skip the pattern and focus on what each branch actually does. The payoff is that every place a call can fail is visible right there in the code, not hidden behind a try block three functions up the stack that might or might not catch the right exception type.

Compare to Python: an exception can be raised deep in a call stack and silently propagate through several functions that never mention it, until something (or nothing) catches it. In Go, if divide can fail, every single caller — all the way up — has to explicitly decide what to do about it, because the error is sitting right there as a value they asked for.

panic and recover — the actual exception mechanism

Go does have something exception-like: panic. But it's reserved for programmer errors and truly unrecoverable situations (an out-of-bounds slice access, a nil pointer dereference), not for expected failure modes like "the file wasn't found" or "the divisor was zero." Those get a returned error. You'll see panic/recover properly in a later lesson — for now, the rule of thumb is: if it's expected, return an error; if it should never happen, let it panic.

Lesson page →

Composite Types

Arrays

Arrays: fixed size, rarely used directly

var scores [3]int
scores[0] = 90
scores[1] = 85
scores[2] = 78
Go

An array's length is part of its type — [3]int and [5]int are different types, not just different lengths of the same type. That's rigid enough that you'll rarely declare a bare array in everyday Go. What you'll actually use, constantly, is a slice — next lesson.

Lesson page →

Slices

Slices: the type you'll use for almost everything list-shaped

A slice looks similar to an array but has no fixed length:

names := []string{"Ada", "Grace", "Haleh"}
fmt.Println(len(names)) // 3
Go

Notice the type: []string, no number inside the brackets — that's what makes it a slice, not an array. Under the hood, a slice is a small struct holding a pointer to an underlying array, a length, and a capacity — but you rarely need to think about that to use one.

Growing a slice
var names []string          // nil slice, len 0
names = append(names, "Ada")
names = append(names, "Grace")
fmt.Println(names) // [Ada Grace]
Go

append is a built-in function, not a method — you call append(slice, value), not slice.append(value), and you must reassign the result. This trips up everyone coming from a language with mutable list methods: append(names, "X") on its own does nothing to names, because a slice may need to be reallocated to grow (if the underlying array is full, append allocates a bigger one and copies everything over), so the only reliable way to see the new slice is the one append hands back.

Slicing a slice

The operation that gives slices their name — carving out a sub-range with s[low:high], low inclusive, high exclusive:

nums := []int{10, 20, 30, 40, 50}
fmt.Println(nums[1:3]) // [20 30]
fmt.Println(nums[:2])  // [10 20]
fmt.Println(nums[2:])  // [30 40 50]
Go

This is a view into the same underlying array, not a copy — mutating an element through one slice can be visible through another slice that overlaps it. This matters mostly when you pass slices between functions and both sides keep working with them; if you need an independent copy, use the built-in copy:

original := []int{1, 2, 3}
duplicate := make([]int, len(original))
copy(duplicate, original)
Go

make([]int, 3) creates a slice of length 3, pre-filled with the zero value (0 for int) — the idiomatic way to allocate a slice you're about to fill in, when you don't have literal values up front the way []int{1, 2, 3} does.

Iterating
for i, n := range nums {
	fmt.Println(i, n)
}
Go

Same range you saw with control flow — it works identically over arrays and slices.

Strings are close cousins of byte slices

A Go string is UTF-8 encoded and immutable, and len(s) gives you the number of bytes, not necessarily the number of characters (a multi-byte character like é counts as more than one). Ranging over a string with for i, r := range s gives you Unicode code points (runes), not bytes — the one place Go's range behaves a little differently depending on what you're ranging over. You won't need this distinction often, but it's worth knowing it's there before it surprises you on non-ASCII input.

Lesson page →

Slice Capacity

Capacity: how much room a slice has

The slices lesson said a slice holds a pointer to a backing array, a length, and a capacity. You've been using the length — here's the third number:

  • len(s) — how many elements the slice holds right now.
  • cap(s) — how many it could hold before Go has to swap in a bigger backing array.
s := make([]int, 3)
fmt.Println(len(s), cap(s)) // 3 3
Go

slice-capacity-anatomy-01.svg

Go grows the capacity for you

When you append and the backing array is already full, Go quietly allocates a bigger one, copies the existing elements across, and adds the new element there — you never do this by hand:

var s []int
for i := 0; i < 6; i++ {
	s = append(s, i)
	fmt.Println(len(s), cap(s))
}
// 1 4
// 2 4
// 3 4
// 4 4
// 5 8
// 6 8
Go

The capacity jumps in chunks — roughly doubling each time — so these reallocations get rarer as the slice grows and append stays cheap on average. The exact numbers vary by Go version; don't write code that depends on them.

slice-append-grow-01.svg

Ask for the size up front when you know it

If you already know how many elements you're about to add, the three-argument make lets you set the capacity now:

nums := make([]int, 0, 100) // len 0, cap 100
Go

Appending 100 times to nums allocates nothing extra — the backing array is already big enough.

Lesson page →

Maps

Maps

A map is Go's key-value type — the equivalent of a Python dict:

ages := map[string]int{
	"Ada":   36,
	"Grace": 85,
}
 
fmt.Println(ages["Ada"]) // 36
Go

Add or update a key with plain assignment, no append-style reassignment needed (unlike slices, a map is a reference type that's already safe to mutate in place):

ages["Haleh"] = 34
Go
The two-value lookup

Looking up a missing key doesn't panic or return an error — it silently returns the value type's zero value, which is genuinely dangerous if you don't know to check for it:

fmt.Println(ages["Nobody"]) // 0 — looks like a real age!
Go

The fix is the two-value form, the same value, ok pattern you saw with if:

age, ok := ages["Nobody"]
if !ok {
	fmt.Println("not found")
}
Go

You'll write this constantly enough that it becomes reflexive — any time a missing key is meaningfully different from a zero value, use the two-value form.

Deleting and iterating
delete(ages, "Ada")
 
for name, age := range ages {
	fmt.Println(name, age)
}
Go

One thing to know up front: map iteration order is randomized on purpose, on every run. If you need a stable order, sort the keys yourself first — Go deliberately doesn't give you a stable default, specifically so nobody accidentally depends on an ordering that was never guaranteed.

Lesson page →

Structs

Structs

A struct groups related fields under one named type — the closest thing Go has to a class, minus inheritance:

type Person struct {
	Name string
	Age  int
}
 
p := Person{Name: "Haleh", Age: 34}
fmt.Println(p.Name) // Haleh
 
p.Age = 35 // structs are mutable by default
Go

Capitalized field names (Name, Age) are exported outside the package, same rule as everywhere else in Go — lowercase them (name, age) if a field should stay package-private.

Structs are values, not references

This is the detail most likely to surprise you coming from Python or JavaScript, where assigning or passing an object just copies a reference to the same underlying data. In Go, assigning a struct — or passing one to a function — copies the whole thing:

p1 := Person{Name: "Ada", Age: 36}
p2 := p1
p2.Name = "Grace"
 
fmt.Println(p1.Name) // Ada — unchanged
fmt.Println(p2.Name) // Grace
Go

p2 is an independent copy; modifying it never touches p1. This is exactly the kind of behavior that will bite you once — pass a struct to a function expecting to mutate the caller's copy, and watch the caller's copy stay unchanged — before it clicks. The fix, once you need it, is a pointer to the struct instead of the struct itself, which you'll see properly in the next module.

Nested structs
type Address struct {
	City    string
	Country string
}
 
type Person struct {
	Name    string
	Age     int
	Address Address
}
 
p := Person{
	Name: "Haleh",
	Age:  34,
	Address: Address{
		City:    "Toronto",
		Country: "Canada",
	},
}
 
fmt.Println(p.Address.City) // Toronto
Go

Composing small structs like this — rather than one large flat one — is the idiomatic way to model related-but-distinct groups of fields, and it sets up naturally for the methods and interfaces you'll meet next.

Lesson page →

Pointers, Methods, and Interfaces

Pointers

You saw &fahrenheit back in the very first exercise, with a promise to explain it properly later. Here's later.

What a pointer is

A pointer holds the memory address of a value, instead of the value itself. Two operators do all the work:

  • &x — "give me the address of x" — produces a pointer to x.
  • *p — "give me the value at the address p points to" — dereferences a pointer.
x := 10
p := &x        // p is a *int, pointing at x
fmt.Println(*p) // 10
 
*p = 20         // write through the pointer
fmt.Println(x)  // 20 — x itself changed
Go

p's type is *int — "pointer to int." Assigning through *p writes to the same memory x lives in, which is why changing *p changes x too.

Why you need this given structs are copied by value

Recall from the last module: assigning or passing a struct copies it. That's often exactly what you want — a copy can't be accidentally mutated by code elsewhere. But sometimes you want a function to modify the caller's actual data. A pointer is how:

type Person struct {
	Name string
	Age  int
}
 
func birthday(p *Person) {
	p.Age++
}
 
haleh := Person{Name: "Haleh", Age: 34}
birthday(&haleh)
fmt.Println(haleh.Age) // 35
Go

Without the pointer, birthday would receive a copy, increment the copy's Age, and the caller's haleh would be untouched. &haleh passes the address instead, so p.Age++ reaches through to the original.

Notice p.Age++, not (*p).Age++ — Go automatically dereferences a pointer when you access a field through it. You only need the explicit * when you're working with the whole value the pointer points to, not one of its fields.

Go still has garbage collection

This is a common early worry, so it's worth saying explicitly: Go is garbage collected, same as Python. You never call free(), there's no manual memory management, and you can return a pointer to a local variable from a function and it just works — Go's compiler figures out that the variable needs to outlive the function call and allocates it accordingly:

func newPerson(name string) *Person {
	p := Person{Name: name}
	return &p // safe — Go keeps p alive as long as something points to it
}
Go

In a language like C, returning the address of a local variable is a classic bug (the stack frame it lived in is gone once the function returns). Go's garbage collector makes that impossible — pointers exist here for control over sharing and mutation, not because you're expected to manage memory by hand.

nil pointers

A pointer's zero value is nil — "points at nothing." Dereferencing a nil pointer panics at runtime:

var p *Person
fmt.Println(p.Name) // panic: invalid memory address or nil pointer dereference
Go

This is the Go equivalent of Python's AttributeError: 'NoneType' object has no attribute ... — same root cause (something you expected to be set wasn't), surfacing as a crash instead of a caught exception. Checking if p != nil before dereferencing is the standard defense, exactly like checking if x is not None in Python.

When to use a pointer

A rough rule of thumb, not a hard law: pass a pointer when the function needs to modify the caller's data, or when the value is large enough that copying it repeatedly would be wasteful. For small values you're not modifying — an int, a small struct you're only reading — passing by value is simpler and avoids giving the function more power over your data than it needs.

Lesson page →

Methods

Go has no class keyword. Instead, you attach functions to types with a receiver.

Methods

A method is a function with an extra parameter before its name — the receiver — that determines which type it's attached to:

type Rectangle struct {
	Width, Height float64
}
 
func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}
 
rect := Rectangle{Width: 3, Height: 4}
fmt.Println(rect.Area()) // 12
Go

(r Rectangle) is the receiver — read it as "this method is attached to Rectangle, and inside the method, the receiving value is called r." Calling rect.Area() is just Area(rect) with nicer syntax.

Value receivers vs. pointer receivers

Just like passing a struct to a plain function, a value receiver ((r Rectangle)) gets a copy — fine for reading, useless for mutating. A pointer receiver ((r *Rectangle)) can modify the original:

func (r *Rectangle) Scale(factor float64) {
	r.Width *= factor
	r.Height *= factor
}
 
rect := Rectangle{Width: 3, Height: 4}
rect.Scale(2)
fmt.Println(rect) // {6 8}
Go

Notice you call rect.Scale(2), not (&rect).Scale(2) — Go automatically takes the address for you when you call a pointer-receiver method on an addressable value. The rule of thumb: if a method needs to mutate the receiver, or the struct is large enough that copying it is wasteful, use a pointer receiver. Otherwise a value receiver is simpler. Mixing both styles on the same type is legal but considered bad style — pick one per type and stay consistent.

Lesson page →

Interfaces

Interfaces

An interface defines a set of methods a type must have — without that type ever declaring which interfaces it implements. This is the biggest structural difference from class-based inheritance you're likely used to:

type Shape interface {
	Area() float64
}
Go

Any type with an Area() float64 method automatically satisfies Shape — no Rectangle implements Shape anywhere:

type Circle struct {
	Radius float64
}
 
func (c Circle) Area() float64 {
	return 3.14159 * c.Radius * c.Radius
}
 
func printArea(s Shape) {
	fmt.Println(s.Area())
}
 
printArea(Rectangle{Width: 3, Height: 4}) // 12
printArea(Circle{Radius: 2})              // 12.56636
Go

printArea doesn't know or care whether it received a Rectangle or a Circle — only that whatever it got has an Area() float64 method. This is called structural typing: satisfying an interface is about having the right shape, not about declaring a relationship. It's the same idea as Python's duck typing ("if it walks like a duck and quacks like a duck..."), except Go checks it at compile time instead of discovering a missing method at runtime.

Why this matters in practice

Structural typing means you can define a small interface for exactly what your function needs, and any existing type — including ones from a library you don't control and can't modify — satisfies it automatically as long as it has the right methods. You never need to go back and retrofit an implements declaration onto a type just so it can be used somewhere new.

The empty interface and any

interface{} (aliased as any in modern Go) has zero required methods, so every type satisfies it:

func describe(v any) {
	fmt.Printf("value: %v, type: %T\n", v, v)
}
 
describe(42)        // value: 42, type: int
describe("hello")   // value: hello, type: string
Go

This is Go's escape hatch for "I genuinely don't know the type ahead of time" — used sparingly, since it gives up the compile-time type checking that's most of the point of using Go in the first place.

Lesson page →

Concurrency

Goroutines

This is the module where Go stops looking like "a stricter Python" and starts looking like a language actually designed for concurrent programs from day one — not with a library bolted on later, but with a keyword.

Launching a goroutine

func sayHello() {
	fmt.Println("hello from a goroutine")
}
 
func main() {
	go sayHello()
	fmt.Println("hello from main")
}
Go

go sayHello() starts sayHello running concurrently with the rest of main — Go doesn't wait for it to finish before moving to the next line. Run this and you might see either line print first, or — very likely — see only "hello from main" at all:

hello from main

That's not a bug. main returning ends the whole program immediately, goroutines and all, the same way closing a terminal kills every child process running in it. A goroutine isn't guaranteed to run to completion unless something makes the rest of the program wait for it — which is exactly the problem channels (next lesson) and sync.WaitGroup exist to solve.

Why goroutines aren't threads (even though they look like it)

If you've used threads in another language, go someFunc() looks a lot like spawning a thread. The similarity is intentional, but the cost isn't: an OS thread typically reserves a megabyte or more of stack space and costs real time for the OS scheduler to context-switch. A goroutine starts with a stack of only a few kilobytes that grows and shrinks as needed, and Go's own runtime scheduler — not the OS — multiplexes many goroutines onto a much smaller number of real OS threads.

The practical result: spinning up thousands, even hundreds of thousands, of goroutines is normal and cheap in Go. Spinning up that many OS threads would bring most machines to their knees. This is why Go code reaches for go someFunc() as casually as other languages reach for a plain function call — handling every incoming HTTP request in its own goroutine, for instance, is the default way Go's standard net/http server works, not an optimization someone had to opt into.

WaitGroup: waiting for goroutines to finish

The most common way to make main (or any function) wait for a batch of goroutines is sync.WaitGroup:

import "sync"
 
func main() {
	var wg sync.WaitGroup
 
	for i := 1; i <= 3; i++ {
		wg.Add(1)
		go func(n int) {
			defer wg.Done()
			fmt.Println("worker", n)
		}(i)
	}
 
	wg.Wait()
	fmt.Println("all workers done")
}
Go

Three things worth naming:

  • wg.Add(1) before launching each goroutine — tell the WaitGroup how many things it's waiting for.
  • defer wg.Done() inside the goroutine — mark this one as finished when the function returns. (You'll see defer properly in a later lesson; for now, read it as "run this when the surrounding function exits.")
  • wg.Wait() — blocks until the count returns to zero.
Why n int is a parameter, not a captured variable

Notice the goroutine is func(n int) { ... }(i) — an anonymous function immediately called with i passed in — rather than just referencing the loop variable i directly from inside the closure. This is deliberate: it's a classic Go bug to write go func() { fmt.Println(i) }() inside a loop and have every goroutine print the same final value of i, because they'd all be sharing and reading the same loop variable, not a snapshot of it at the time they were launched. Passing i in as an argument gives each goroutine its own independent copy. (Go 1.22 changed loop variable semantics so this specific bug is less likely today, but passing it explicitly is still the clearer, more portable habit — and you'll see it in plenty of existing code.)

Goroutines are the foundation. The next lesson covers channels — the primary way goroutines safely communicate with each other, instead of reaching into shared memory directly the way threads usually do.

Lesson page →

Channels

Go has a well-known slogan for how it wants you to handle concurrency: "Do not communicate by sharing memory; instead, share memory by communicating." Channels are the mechanism that makes that possible.

Creating and using a channel

ch := make(chan int)
 
go func() {
	ch <- 42 // send 42 into the channel
}()
 
value := <-ch // receive from the channel
fmt.Println(value) // 42
Go

chan int is a channel that carries int values. ch <- 42 sends; <-ch receives. Both directions block: a send waits until something is ready to receive, and a receive waits until something sends. That blocking is the actual synchronization mechanism — it's what makes value := <-ch in the example above safe to read immediately, without any separate wg.Wait(): the receive simply doesn't proceed until the goroutine has sent.

Why this beats a shared variable with a lock

Contrast with the alternative: two goroutines both reading and writing the same variable, coordinated with a mutex. That works too (Go has sync.Mutex for exactly that), but it requires every piece of code that touches the shared variable to remember to lock and unlock correctly, forever, including code added later by someone who didn't see the original design. A channel makes the handoff itself the shared thing — ownership of the data moves from sender to receiver at the moment of the send, and only one goroutine holds it at a time. There's nothing to forget to lock, because there's no shared variable left to protect.

Buffered channels

make(chan int) above is unbuffered — a send blocks until a receive is ready, right that moment. A buffered channel accepts a fixed number of values without an immediate receiver:

ch := make(chan int, 2)
ch <- 1 // doesn't block — buffer has room
ch <- 2 // doesn't block — buffer now full
ch <- 3 // blocks — buffer is full, waits for a receive to free a slot
Go

Use buffering when a producer can legitimately get a little ahead of its consumer; leave a channel unbuffered by default when you specifically want the "handed off, guaranteed" synchronization an unbuffered send/receive gives you.

Closing a channel and ranging over it

A sender can close(ch) to signal "nothing more is coming." Receivers can detect this, and range over a channel until it's closed:

ch := make(chan int)
 
go func() {
	for i := 1; i <= 3; i++ {
		ch <- i
	}
	close(ch)
}()
 
for v := range ch {
	fmt.Println(v)
}
// prints 1, 2, 3, then the loop ends when ch is closed
Go

Only the sender should close a channel, never the receiver — closing a channel you're only receiving from (or closing one twice) panics.

Lesson page →

Select

select: waiting on multiple channels

select looks like switch, but each case is a channel operation, and it picks whichever one is ready first:

select {
case v := <-ch1:
	fmt.Println("from ch1:", v)
case v := <-ch2:
	fmt.Println("from ch2:", v)
default:
	fmt.Println("neither ready")
}
Go

Without a default case, select blocks until one of the channel operations can proceed. With one, it returns immediately if nothing's ready — the non-blocking check. This is the tool for the common case of "wait for whichever of these several things finishes first" — for instance, a result channel and a timeout channel (time.After) raced against each other, so a slow operation doesn't hang your program forever.

Goroutines, channels, buffering, and select are the whole toolkit. Nearly everything you'll see in real concurrent Go code, including the concurrency chapters of this site's Operating Systems course, is built by combining them.

Lesson page →

Packages, Modules, and Testing

Packages

Every Go file so far has started with package main. Time to see what that first line actually controls, and how real projects are organized beyond a single file.

Packages: Go's unit of code organization

Every .go file belongs to a package, declared on its first line. Files in the same directory must belong to the same package, and that directory is the package — Go has no separate "module" keyword for grouping files the way some languages do; the folder structure does the job.

// file: shapes/rectangle.go
package shapes
 
type Rectangle struct {
	Width, Height float64
}
 
func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}
Go

Another file, shapes/circle.go, would also start with package shapes and can use Rectangle directly — no import needed for files in the same package.

Only package main produces a runnable program; every other package name marks a library that other code imports. Recall from the very first lesson: only capitalized names (Rectangle, Area) are visible outside the package — that's the mechanism controlling what a package exposes to its importers.

Importing your own package

// file: main.go
package main
 
import (
	"fmt"
	"myproject/shapes"
)
 
func main() {
	r := shapes.Rectangle{Width: 3, Height: 4}
	fmt.Println(r.Area())
}
Go

The import path (myproject/shapes) isn't a filesystem path — it's the module path defined in go.mod, plus the subdirectory. Which brings us to modules, next.

Lesson page →

Modules

go.mod: dependencies and the module path

A module is Go's unit of dependency versioning — one go.mod file at the root of a project, declaring the module's own import path and every external package it depends on:

go mod init myproject
Shell

produces:

module myproject
 
go 1.23

Add a dependency by importing it in code and running:

go get github.com/some/package
go mod tidy
Shell

go get fetches the package and records the exact version in go.mod; go mod tidy reconciles go.mod (and the generated go.sum, which pins exact checksums) with what your code actually imports — adding anything missing, removing anything unused. This is the closest Go equivalent to Python's requirements.txt/pyproject.toml, except versions and checksums are locked automatically rather than being something you maintain by hand.

Standard library packages need no module at all

Everything you've imported so far — fmt, sync — ships with the Go toolchain itself and needs no go get, no entry in go.mod, nothing beyond the import line. The standard library is large and used constantly in idiomatic Go; reaching for a third-party package for something the standard library already does well (HTTP servers, JSON encoding, string manipulation) is often considered unidiomatic rather than pragmatic, the opposite of the instinct in some ecosystems.

A minimal project layout

myproject/
  go.mod
  main.go
  shapes/
    rectangle.go
    circle.go

Nothing here is enforced by the compiler beyond "each directory is one package" — but this shape (a main.go at the root, feature code split into subdirectory packages) is what you'll see in the overwhelming majority of real Go projects, including the standard library's own source.

Lesson page →

Testing

Go ships a test runner as part of the standard toolchain — no pytest to install. A test lives in a file named *_test.go, in the same package as the code it tests:

// file: shapes/rectangle.go
package shapes
 
func Area(width, height float64) float64 {
	return width * height
}
Go
// file: shapes/rectangle_test.go
package shapes
 
import "testing"
 
func TestArea(t *testing.T) {
	got := Area(3, 4)
	want := 12.0
 
	if got != want {
		t.Errorf("Area(3, 4) = %v, want %v", got, want)
	}
}
Go

The conventions are all load-bearing, not stylistic preference: the file must end in _test.go, the function must start with Test, and it must take exactly one parameter, t *testing.T. Run every test in the current package with:

go test ./...
Shell

t.Errorf records a failure and lets the test function continue running (useful for reporting multiple problems from one test); t.Fatalf records a failure and stops that test function immediately — reach for it when a later assertion in the same test would panic on bad data if you tried to run it after an earlier check has already failed. There's no separate assertion library in the standard toolchain — you write the if yourself and call t.Errorf in the failing branch. This feels sparse coming from pytest or unittest's richer set of assertion helpers, but it means a Go test is just... a Go function, with no framework-specific DSL to learn beyond the one *testing.T parameter.

Table-driven tests

A pattern you'll see constantly in real Go code — one test function, many cases, via a slice of structs:

func TestArea(t *testing.T) {
	cases := []struct {
		width, height, want float64
	}{
		{3, 4, 12},
		{5, 5, 25},
		{0, 4, 0},
	}
 
	for _, c := range cases {
		got := Area(c.width, c.height)
		if got != c.want {
			t.Errorf("Area(%v, %v) = %v, want %v", c.width, c.height, got, c.want)
		}
	}
}
Go

This is idiomatic Go doing what a pytest.mark.parametrize decorator does in Python — except it's just a slice literal and a loop, using nothing beyond what you already know.

Lesson page →

defer

defer schedules a call to run right before the surrounding function returns, no matter which return statement triggers it — including one triggered by a later panic. It's overwhelmingly used for cleanup:

func readFile(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
 
	// ... use f ...
	return nil
}
Go

Reading top to bottom: open the file, and immediately say "close it when this function ends" — right next to the open, not scattered across every possible early-return path further down. That proximity is the whole value: in a function with several if err != nil { return err } early exits, remembering to close a resource before each one is exactly the kind of thing that's easy to miss. One defer, right after the resource is acquired, covers every exit path automatically.

Deferred calls run in last-in-first-out order if there are several, and their arguments are evaluated immediately (at the defer line), even though the call itself happens later.

Lesson page →

When defer Runs, and When It Doesn't

In the last lesson, defer scheduled a call to run "right before the surrounding function returns." That sentence is true. It also has two small conditions hiding inside it, and the best way to find them is to try to break it.


Student So defer means "run this at the end of the function." Where's the catch?

Professor Sage There isn't a catch in that sentence — it's the right picture. Let's make it precise by testing it. Start with the plain case:

package main
 
import "fmt"
 
func main() {
	fmt.Println("start")
	defer fmt.Println("deferred")
	fmt.Println("end of main")
}
Go

What do you expect to see?

Student start, then end of main, then deferred — the deferred line waits until main is done.

Professor Sage Run it:

start
end of main
deferred

Exactly your prediction. Now a harder test. What happens if we put a return before the defer line?

package main
 
import "fmt"
 
func main() {
	fmt.Println("start")
	return
	defer fmt.Println("deferred")
}
Go

Student main returns, so... deferred still prints? You said it runs when the function returns.

Professor Sage Run it and see.

start

Student It never printed. But the function did return!

Professor Sage It did. So the sentence needs one more word. Think about what defer really is: not a label that Go reads ahead of time, but a statement that executes in order, like fmt.Println does. When execution reaches a defer line, Go stores that call in a list. When the function returns, Go runs whatever is in the list. In our second program, the return came first. Execution never reached the defer line, so nothing was ever stored, so nothing ran.

go vet notices this too:

main.go:8:2: unreachable code

Student So the rule is: a deferred call runs when the function returns, provided the defer line was reached first.

Professor Sage That's the full rule, and you said it better than I did. It's why you see defer f.Close() written immediately after the if err != nil { return err } that follows os.Open. If the open failed, you return early, and there is nothing to close. Once the file exists, you want the defer registered before any other code gets a chance to return.

Student Okay. Now a third test, I think. What if the function doesn't return, but the program just exits?

Professor Sage Good instinct. Try it with log.Fatalf, which prints a message and ends the program:

package main
 
import (
	"fmt"
	"log"
)
 
func main() {
	fmt.Println("start")
	defer fmt.Println("deferred")
	log.Fatalf("exit the program")
}
Go

This time the defer line is reached, before log.Fatalf. What do you predict?

Student The defer was registered, and main is ending... so deferred prints?

Professor Sage Run it.

start
2026/10/04 21:29:26 exit the program
exit status 1

Student No deferred again! But this time it was registered. So what's different from the first experiment?

Professor Sage In the first experiment, main returned but the defer was never registered. Here the defer was registered, but main never returned. log.Fatalf ends with a call to os.Exit(1), and os.Exit doesn't unwind the stack and return through your functions. It asks the operating system to end the whole process, right now, in the middle of whatever line it was on. The list of deferred calls is just part of that process's memory, and the process is gone before anyone reads it.

If you replace log.Fatalf("exit the program") with a plain return, you get the deferred line back, because now main really does return.

Student So there are two separate ways for a deferred call to be skipped.

Professor Sage Yes, and they fail for opposite reasons. Here they are side by side:

SituationWas defer reached?Did the function return?Deferred call runs?
defer, then normal end or returnyesyesyes
return before the defer linenoyesno
defer, then log.Fatalf or os.Exityesnono

Student What about a panic? That also stops the function in the middle.

Professor Sage A good one to separate. A panic does run deferred calls as it unwinds, which is exactly what makes recover possible — that's the next lesson. os.Exit and log.Fatal are different because they skip the unwinding entirely.

Student Does it matter in practice? If the process is dying anyway, who cares if Close() didn't run?

Professor Sage Often it genuinely doesn't: when a process ends, the operating system closes its open files and network connections for you. It starts to matter when the deferred call does real work — flushing a buffered writer so the last lines of output aren't lost, removing a temporary file, releasing a lock file, writing a final log line. Skipping those can leave a mess behind.

Student Then how do I report a fatal error without skipping them?

Professor Sage Put the real work in a function that returns an error, and let only main decide to exit:

func run() error {
	f, err := os.Create("out.txt")
	if err != nil {
		return err
	}
	defer f.Close() // runs when run() returns, even on the error paths below
 
	// ... work that may return an error ...
	return nil
}
 
func main() {
	if err := run(); err != nil {
		log.Fatalf("failed: %v", err) // by now run() has returned, so its defers already ran
	}
}
Go

run returns, so its deferred calls run. Only after that does main call log.Fatalf, and by then there is nothing left to skip. This run() error shape is common in real Go programs for exactly this reason.


Definitions

  • Registering a deferred call — what happens when execution reaches a defer statement: Go evaluates the call's arguments immediately and stores the call to run later. A defer line that is never reached never registers anything.
  • Deferred call runs — when the surrounding function returns (by reaching its end, by a return, or while a panic unwinds it), Go runs the registered calls in last-in-first-out order.
  • os.Exit(code) — ends the whole process immediately with the given exit status. It does not return to the caller and does not run any deferred calls.
  • log.Fatal, log.Fatalf, log.Fatalln — print a message to the log, then call os.Exit(1). They skip deferred calls for the same reason os.Exit does.
  • Exit status — the number a process hands back to whoever started it. 0 means success; anything else means failure. Cron jobs and shell scripts read it.

Takeaways

What we established

  • A defer is a statement that executes in order. A deferred call runs when its function returns, but only if execution reached the defer line first.
  • A return placed before a defer line means that defer is never registered.
  • log.Fatalf and os.Exit end the process without returning from any function, so even deferred calls that were registered are skipped.
  • Putting defer right after the code that acquires a resource, and keeping log.Fatal out of the functions that hold resources (do it once in main), keeps cleanup reliable.

What's still open we've seen that panic runs deferred calls while it unwinds, but not what a deferred function can do with a panic. That is the job of recover, in the next lesson.

Lesson page →

panic and recover

You met the rule of thumb back in the functions/errors lessons: expected failures return an error; panic is for what should never happen. panic immediately stops normal execution, running any deferred calls on the way up, then crashes the program — unless something calls recover.

func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered from panic: %v", r)
		}
	}()
 
	return a / b, nil // dividing by zero panics
}
Go

recover() only does anything inside a deferred function, and only stops a panic that's actively unwinding — calling it in ordinary code does nothing. This pattern (defer a function that calls recover, and turn the panic into a regular error) is how a long-running program — a web server handling one request among thousands — survives an unexpected panic in one request-handling goroutine without taking the whole process down. It's the exception, not the rule: most Go code never calls recover, because most Go code is careful to make sure it never panics in the first place. That instinct — push failure handling into an explicit, checked return value rather than an escape hatch you reach for at the last second — is the thread running through everything in this course.

Lesson page →