DEV Community

Cover image for Go workbook: 10 predict-the-output exercises that test first principles (with answers)
Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on

Go workbook: 10 predict-the-output exercises that test first principles (with answers)

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

  1. Read an exercise.
  2. Write your prediction down, on paper or in a file. Not in your head: a vague guess always feels right afterwards.
  3. Open the answer and compare.
  4. Score yourself: 1 point for the exact output, half a point for the right idea with a detail wrong.
  5. 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

  1. Two appends, one base
  2. How big is this struct?
  3. Map iteration order
  4. Defer: order and evaluation
  5. The nil map
  6. Bytes versus characters
  7. The goroutine that never ends
  8. Integers at the edge
  9. Where did my error go?
  10. Closed channels
  11. Bonus 1: the error that isn't nil
  12. Bonus 2: ranging over a string
  13. Score yourself
  14. 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)
Enter fullscreen mode Exit fullscreen mode

What does it print?

Answer
[0 0 2] [0 0 2]
Enter fullscreen mode Exit fullscreen mode

Not [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.

Principle (strategy 2, data structures as runtime objects): a slice is a pointer, a length and a capacity. append only allocates when capacity runs out.

Fix: cap the base so 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))
Enter fullscreen mode Exit fullscreen mode

Three fields: 1 + 4 + 1 = 6 bytes. Right?

Answer
12 4
Enter fullscreen mode Exit fullscreen mode

Twelve bytes, double the sum. An 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)
Enter fullscreen mode Exit fullscreen mode

The trailing padding is the subtle part: the struct's size is rounded up to a multiple of its largest alignment, so that in []T every element's b is aligned too.

Principle (strategy 3, how types work): layout is part of the type. Reorder to 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, " ")
}
Enter fullscreen mode Exit fullscreen mode

Does it print abcde abcde abcde?

Answer

My run:

abcde abcde bcdea
Enter fullscreen mode Exit fullscreen mode

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, slices.Sort(keys), then iterate.


Exercise 4: defer, order and evaluation

Two parts. First:

for i := 0; i < 3; i++ {
    defer fmt.Print(i, " ")
}
Enter fullscreen mode Exit fullscreen mode

Then, in another function:

v := 1
defer fmt.Println("arg evaluated at defer:", v)
defer func() { fmt.Println("closure sees:", v) }()
v = 2
Enter fullscreen mode Exit fullscreen mode

Answer
2 1 0
closure sees: 2
arg evaluated at defer: 1
Enter fullscreen mode Exit fullscreen mode

Two rules at once:

  • Deferred calls run last-in, first-out, like a stack. So 2 1 0, and in the second function the closure (deferred last) runs first.
  • Arguments are evaluated when 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.

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 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
Enter fullscreen mode Exit fullscreen mode

Does the read panic? The write?

Answer
read from nil map: 0 0
write to nil map: assignment to entry in nil map
Enter fullscreen mode Exit fullscreen mode

(The second line is from a recover in the full program; without it, the program crashes.)

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 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] == "🍌")
Enter fullscreen mode Exit fullscreen mode

"ndizi" is Swahili for banana. Seven characters, so len is 7?

Answer
10 7 false
Enter fullscreen mode Exit fullscreen mode

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.

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 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)
Enter fullscreen mode Exit fullscreen mode

The function containing the loop has returned. Are the goroutines gone?

Answer
leaked goroutines: 100
Enter fullscreen mode Exit fullscreen mode

All 100 are still there, blocked forever on 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.

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 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)
Enter fullscreen mode Exit fullscreen mode

Panic? Error?

Answer
-128 18446744073709551615
Enter fullscreen mode Exit fullscreen mode

Neither. Go integers wrap around silently (two's complement). int8 max plus one is its minimum; uint zero minus one is its maximum, 2⁶⁴ − 1.

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.

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)
Enter fullscreen mode Exit fullscreen mode

Answer
outer err: <nil>
Enter fullscreen mode Exit fullscreen mode

:= 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.

Principle (strategy 7, stop copy-pasting): := 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)
Enter fullscreen mode Exit fullscreen mode

Answer
7 true 0 false
close twice: close of closed channel
Enter fullscreen mode Exit fullscreen mode
  • Closing a channel doesn't discard buffered values: the first receive still gets 7, with ok = true.
  • Once drained, receives on a closed channel never block: they return the zero value immediately, with ok = false. That's how for v := range ch knows to stop.
  • Closing twice panics. So does sending on a closed channel.

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.

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))
Enter fullscreen mode Exit fullscreen mode

The payment succeeded. Does err == nil say so?

Answer
false *main.PaymentError
Enter fullscreen mode Exit fullscreen mode

No. An interface value is a pair: (dynamic type, value). 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.

Principle (strategy 3): interfaces are runtime pairs. A function returning an interface type must return a literal 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)
}
Enter fullscreen mode Exit fullscreen mode

What are the indexes?

Answer
0:n 1:d 2:i 3:z 4:i 5:  6:🍌 10:!
Enter fullscreen mode Exit fullscreen mode

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.

Principle (strategy 2): strings are bytes; 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)
    }()
}
Enter fullscreen mode Exit fullscreen mode

mkdir workbook && cd workbook
go mod init workbook      # make sure go.mod says go 1.22 or newer
# save main.go, then:
go run .
Enter fullscreen mode Exit fullscreen mode

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)