The short version: This is the hands-on companion to "10 First-Principles Strategies to Learn Any Programming Language Deeply". Ten small Go programs. For each one: read the code, write down what you think it prints, then open the answer. Every answer is the real output from Go 1.26.5, with the principle that explains it. If you get all ten right before opening any answer, you understand Go's memory, types and concurrency better than most people who use it daily.
How to use this workbook
- Read an exercise.
- Write your prediction down, on paper or in a file. Not in your head: a vague guess always feels right afterwards.
- Open the answer and compare.
- Score yourself: 1 point for the exact output, half a point for the right idea with a detail wrong.
- For every miss, read the principle and re-run the code with one change of your own.
All ten exercises are one program at the end, so you can run them yourself (go run .). Your machine may differ in exactly one place (exercise 3), and that's the point of exercise 3.
Contents
- Two appends, one base
- How big is this struct?
- Map iteration order
- Defer: order and evaluation
- The nil map
- Bytes versus characters
- The goroutine that never ends
- Integers at the edge
- Where did my error go?
- Closed channels
- Bonus 1: the error that isn't nil
- Bonus 2: ranging over a string
- Score yourself
- The whole program
Exercise 1: two appends, one base
base := make([]int, 2, 4)
x := append(base, 1)
y := append(base, 2)
fmt.Println(x, y)
What does it print?
Not Principle (strategy 2, data structures as runtime objects): a slice is a pointer, a length and a capacity. Fix: cap the base so Answer
[0 0 2] [0 0 2]
[0 0 1] [0 0 2]. base has length 2 and capacity 4, so the first append writes 1 into slot 2 of the existing backing array, and the second writes 2 into the same slot. x and y are two headers over one array.append only allocates when capacity runs out.append must copy: base[:2:2], or slices.Clip(base).
Exercise 2: how big is this struct?
type T struct {
a byte
b int32
c byte
}
fmt.Println(unsafe.Sizeof(T{}), unsafe.Alignof(T{}.b))
Three fields: 1 + 4 + 1 = 6 bytes. Right?
Twelve bytes, double the sum. An The trailing padding is the subtle part: the struct's size is rounded up to a multiple of its largest alignment, so that in Principle (strategy 3, how types work): layout is part of the type. Reorder to Answer
12 4
int32 must start at an address divisible by 4 (its alignment, the second number). So:
offset 0 a 1 byte
offset 1-3 pad 3 bytes (so b starts at 4)
offset 4-7 b 4 bytes
offset 8 c 1 byte
offset 9-11 pad 3 bytes (so an array of T keeps every b aligned)
[]T every element's b is aligned too.b int32; a byte; c byte and it shrinks to 8.
Exercise 3: map iteration order
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
for r := 0; r < 3; r++ {
s := ""
for k := range m {
s += k
}
fmt.Print(s, " ")
}
Does it print abcde abcde abcde?
My run: Your run will likely differ, and may differ every time. Go deliberately randomises the starting point of map iteration, so that nobody writes code that depends on an order the language never promised. If an early Go map happened to return insertion order on your machine, someone would rely on it, and a later runtime change would silently break their program. Randomisation turns that future bug into an immediate one. Principle (strategy 5, understand the runtime): a map is a hash table; its order is an implementation detail, and Go makes sure you notice. Need order? Collect the keys, Answer
abcde abcde bcdea
slices.Sort(keys), then iterate.
Exercise 4: defer, order and evaluation
Two parts. First:
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ")
}
Then, in another function:
v := 1
defer fmt.Println("arg evaluated at defer:", v)
defer func() { fmt.Println("closure sees:", v) }()
v = 2
Two rules at once: Principle (strategy 1, memory before syntax): a closure holds a reference to the variable; a function argument is a copy of the value at that moment. (On Go 1.22+, each loop iteration gets a fresh Answer
2 1 0
closure sees: 2
arg evaluated at defer: 1
2 1 0, and in the second function the closure (deferred last) runs first.defer runs, not when the call runs. fmt.Println("...", v) captured v = 1 at the defer line. The closure captured the variable v, and read it at the end, after it became 2.i, which is why the first part prints 2 1 0 and not 3 3 3 even when written with closures.)
Exercise 5: the nil map
var nm map[string]int
fmt.Println("read from nil map:", nm["x"], len(nm))
nm["x"] = 1
Does the read panic? The write?
(The second line is from a Reading a nil map is fine: it behaves like an empty map and returns the zero value. Writing panics. A nil map has no hash table to write into, and Go won't allocate one behind your back. Principle (strategy 2): a map variable is a single pointer (8 bytes, measured in part 1). Nil means "no table yet". Always Answer
read from nil map: 0 0
write to nil map: assignment to entry in nil map
recover in the full program; without it, the program crashes.)make a map, or use a composite literal, before writing.
Exercise 6: bytes versus characters
fruit := "ndizi 🍌"
fmt.Println(len(fruit), utf8.RuneCountInString(fruit), fruit[6:7] == "🍌")
"ndizi" is Swahili for banana. Seven characters, so len is 7?
Principle (strategy 3): a Go string is a read-only slice of bytes (pointer and length, 16 bytes). Text is an interpretation of those bytes. Use Answer
10 7 false
len counts bytes, not characters. "ndizi " is 6 bytes; the banana emoji is 4 bytes in UTF-8. So 10 bytes, 7 runes (characters). And fruit[6:7] is the first byte of the emoji, a fragment of invalid UTF-8, not the emoji.range over a string, or utf8 functions, to work with characters, and never cut user text at an arbitrary byte index.
Exercise 7: the goroutine that never ends
before := runtime.NumGoroutine()
for i := 0; i < 100; i++ {
ch := make(chan int)
go func() { ch <- 42 }() // nobody ever receives
}
time.Sleep(50 * time.Millisecond)
fmt.Println("leaked goroutines:", runtime.NumGoroutine()-before)
The function containing the loop has returned. Are the goroutines gone?
All 100 are still there, blocked forever on This is the most common memory leak in Go services: a goroutine started per request, waiting on a channel that the request's code stopped listening to after a timeout. Principle (strategy 4, concurrency): every goroutine you start needs a way to end. Fixes: a buffered channel of size 1 (the send completes even if nobody reads), or a Answer
leaked goroutines: 100
ch <- 42. An unbuffered send waits for a receiver; nobody will ever receive; the garbage collector does not collect blocked goroutines, and each keeps its stack (at least a few kilobytes) and everything it references alive.select on the send and ctx.Done().
Exercise 8: integers at the edge
var i8 int8 = 127
i8++
var u uint = 0
u--
fmt.Println(i8, u)
Panic? Error?
Neither. Go integers wrap around silently (two's complement). That number matters in money code. Bitcoin had a real bug in 2010 where an overflow in output values let a transaction create about 184 billion bitcoin. Code that handles amounts checks ranges explicitly before arithmetic, and the Lightning wallet code I work on rejects any amount larger than 21 million BTC for that reason. Principle (strategy 1): integers are fixed-width memory, not mathematical numbers. Know the width of every amount you store.Answer
-128 18446744073709551615
int8 max plus one is its minimum; uint zero minus one is its maximum, 2⁶⁴ − 1.
Exercise 9: where did my error go?
func find() (int, error) { return 0, errors.New("not found") }
var err error
if true {
n, err := find()
_ = n
_ = err
}
fmt.Println("outer err:", err)
Principle (strategy 7, stop copy-pasting): Answer
outer err: <nil>
:= inside the if block declared a new err that shadows the outer one. The error was assigned to the inner variable and thrown away at the closing brace. The outer err was never touched.go vet with its default checks didn't flag this (the shadow analyser exists but isn't enabled by default). Linters like staticcheck or golangci-lint with the shadow check will.:= declares; = assigns. When a block needs to set an outer variable, declare the others first (var n int) and use =.
Exercise 10: closed channels
c := make(chan int, 1)
c <- 7
close(c)
v1, ok1 := <-c
v2, ok2 := <-c
fmt.Println(v1, ok1, v2, ok2)
close(c)
Principle (strategy 4): only the sender closes a channel, and only once. Close means "no more values are coming", which is information only the sender has.Answer
7 true 0 false
close twice: close of closed channel
ok = true.ok = false. That's how for v := range ch knows to stop.
Bonus 1: the error that isn't nil
type PaymentError struct{ Reason string }
func (e *PaymentError) Error() string { return e.Reason }
func pay(ok bool) error {
var perr *PaymentError
if !ok {
perr = &PaymentError{Reason: "insufficient balance"}
}
return perr
}
err := pay(true)
fmt.Println(err == nil, fmt.Sprintf("%T", err))
The payment succeeded. Does err == nil say so?
No. An interface value is a pair: (dynamic type, value). Principle (strategy 3): interfaces are runtime pairs. A function returning an interface type must return a literal Answer
false *main.PaymentError
pay(true) returns a nil *PaymentError inside an error interface, so the pair is (*PaymentError, nil). An interface is only nil when both halves are empty. Every caller now treats a successful payment as a failure.nil on success, never a typed nil pointer.
Bonus 2: ranging over a string
for i, r := range "ndizi 🍌!" {
fmt.Printf("%d:%c ", i, r)
}
What are the indexes?
Principle (strategy 2): strings are bytes; Answer
0:n 1:d 2:i 3:z 4:i 5: 6:🍌 10:!
range over a string decodes runes (characters), but the index is the byte offset where each one starts. The banana starts at byte 6 and is 4 bytes long, so the ! that follows is at index 10, not 7. Gaps in the index sequence are the visible footprint of multi-byte characters.range is a UTF-8 decoder on top. If you need character positions, count them yourself; if you need byte positions (to slice safely), this is exactly the number you want.
Score yourself
| Score | What it means |
|---|---|
| 9–12 | You think in memory and runtime, not syntax. Go read the runtime source for maps or channels next. |
| 6–8 | Solid. Your misses map exactly to which strategy to study. |
| 3–5 | Normal for someone who learned Go from tutorials. Redo the misses in a week without looking. |
| 0–2 | Perfect starting point: every exercise you missed is now a fact you'll never forget, because you predicted wrong and saw why. |
The most valuable column isn't the score; it's your written predictions. Keep them. Run the workbook again in a month and compare.
The whole program
main.go (click to expand)
package main
import (
"errors"
"fmt"
"runtime"
"time"
"unicode/utf8"
"unsafe"
)
type T struct {
a byte
b int32
c byte
}
func find() (int, error) { return 0, errors.New("not found") }
func main() {
fmt.Println("== E1 append aliasing")
base := make([]int, 2, 4)
x := append(base, 1)
y := append(base, 2)
fmt.Println(x, y)
fmt.Println("== E2 struct size")
fmt.Println(unsafe.Sizeof(T{}), unsafe.Alignof(T{}.b))
fmt.Println("== E3 map order")
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
for r := 0; r < 3; r++ {
s := ""
for k := range m {
s += k
}
fmt.Print(s, " ")
}
fmt.Println()
fmt.Println("== E4 defer order and evaluation")
func() {
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ")
}
}()
fmt.Println()
func() {
v := 1
defer fmt.Println("arg evaluated at defer:", v)
defer func() { fmt.Println("closure sees:", v) }()
v = 2
}()
fmt.Println("== E5 nil map")
var nm map[string]int
fmt.Println("read from nil map:", nm["x"], len(nm))
func() {
defer func() { fmt.Println("write to nil map:", recover()) }()
nm["x"] = 1
}()
fmt.Println("== E6 bytes vs runes")
fruit := "ndizi 🍌"
fmt.Println(len(fruit), utf8.RuneCountInString(fruit), fruit[6:7] == "🍌")
fmt.Println("== E7 goroutine leak")
before := runtime.NumGoroutine()
for i := 0; i < 100; i++ {
ch := make(chan int)
go func() { ch <- 42 }() // nobody ever receives
}
time.Sleep(50 * time.Millisecond)
fmt.Println("leaked goroutines:", runtime.NumGoroutine()-before)
fmt.Println("== E8 overflow")
var i8 int8 = 127
i8++
var u uint = 0
u--
fmt.Println(i8, u)
fmt.Println("== E9 shadowed err")
var err error
if true {
n, err := find()
_ = n
_ = err
}
fmt.Println("outer err:", err)
fmt.Println("== E10 closed channels")
c := make(chan int, 1)
c <- 7
close(c)
v1, ok1 := <-c
v2, ok2 := <-c
fmt.Println(v1, ok1, v2, ok2)
func() {
defer func() { fmt.Println("close twice:", recover()) }()
close(c)
}()
}
mkdir workbook && cd workbook
go mod init workbook # make sure go.mod says go 1.22 or newer
# save main.go, then:
go run .
Found an exercise where your output differs from mine (other than exercise 3)? Tell me your Go version and platform in the comments; that's a lesson for both of us.
Top comments (0)