Learn Go with AI · Free online book
Chapter 3: Lists, Lookups and Loops
In short: Chapter 3 teaches Go's slices, maps and its one loop keyword, for. Tracker learns to total expenses by category in a stable order, you see why Go maps have no order, and the AI switches from tutor to pair: you write the code and it reviews it.
So far, Tracker knows about one coffee and a hard-coded list of three amounts. Real spending doesn’t work like that. You buy food twice in one day, take a taxi, see a film, and at the end of the month you want to know: where did the money go?
In this chapter, Tracker learns to record expenses by category and total each one. To do that, you’ll go deeper into the two tools Go gives you for groups of values: slices (lists) and maps (lookups). You’ll also meet loops and if properly, and a Go idea that quietly explains a lot of surprises: zero values.
It’s the same SURE loop as before. But halfway through this chapter, something changes.
From tutor to pair
Until now, the AI has been your tutor: it explained, and you typed code from the book. In this chapter, you’ll do both jobs in turn:
- First half: tutor. The AI explains maps and slices, and you type two functions from the book.
- Second half: pair. You write two functions yourself, from the tests. Then you ask the AI to review your code, and you decide which of its suggestions to keep.
That last part is the new skill. A review is a list of suggestions, not orders. Some will be good, some will be fine but unnecessary, and some will be wrong. Deciding which is which is how you learn, and it’s a skill you’ll use for the rest of your career.
Mission
By the end of this chapter, you’ll have:
- A way to add expenses, each with a category and an amount in cents
- Totals for each category, printed in a stable order
- A clear message for a category with no expenses
- Two functions you wrote yourself, reviewed by the AI
- A commit with a
Learned:line
Must know
- A slice is a list that can grow.
appendadds items and returns the new slice, so you always writes = append(s, item).len(s)gives the number of items. - A map looks up a value by its key. In
map[string]int, the keys arestrings and the values areints. You create one withmake(map[string]int). - Every type has a zero value. It’s what a variable holds before you give it anything:
0for numbers,""for strings,falseforbool, andnilfor slices and maps. Looking up a missing map key gives you the zero value, not an error. - A
nilslice is ready to use; anilmap is not. You canappendto a nil slice and take itslen. You can read from a nil map, but writing to one crashes your program. Always create maps withmakebefore writing to them. - Map order is random, on purpose. When you loop over a map, Go may give you the keys in a different order each run. When order matters, collect the keys into a slice and sort it.
Specify
Update SPEC.md so it describes the new Tracker. Keep sentence 1 and replace the rest:
1. `go run .` prints exactly:
Welcome to Tracker. Let's see where your money goes.
2. Tracker records these expenses: Food 3.50, Transport 12.00,
Food 0.99, Fun 15.00.
3. It prints one line per category, sorted by name, with the
category total:
Food: 4.49
Fun: 15.00
Transport: 12.00
4. For a category with no expenses, it prints:
Travel: no expenses
Now turn those sentences into tests. In main_test.go, replace the line import "testing" with this import block, because the new tests use two more packages:
import (
"maps"
"slices"
"testing"
)
Then add these three tests at the end of the file:
func TestTotalsByCategory(t *testing.T) {
expenses := make(map[string][]int)
addExpense(expenses, "Food", 350)
addExpense(expenses, "Transport", 1200)
addExpense(expenses, "Food", 99)
got := totalsByCategory(expenses)
want := map[string]int{"Food": 449, "Transport": 1200}
if !maps.Equal(got, want) {
t.Errorf("totalsByCategory() = %v, want %v", got, want)
}
}
func TestSortedCategories(t *testing.T) {
totals := map[string]int{"Transport": 1200, "Food": 449, "Fun": 1500}
got := sortedCategories(totals)
want := []string{"Food", "Fun", "Transport"}
if !slices.Equal(got, want) {
t.Errorf("sortedCategories() = %v, want %v", got, want)
}
}
func TestDescribeCategory(t *testing.T) {
totals := map[string]int{"Food": 449, "Gifts": 0}
tests := []struct {
category string
want string
}{
{"Food", "Food: 4.49"},
{"Gifts", "Gifts: 0.00"},
{"Travel", "Travel: no expenses"},
}
for _, tt := range tests {
got := describeCategory(totals, tt.category)
if got != tt.want {
t.Errorf("describeCategory(%q) = %q, want %q", tt.category, got, tt.want)
}
}
}
Your Chapter 2 tests stay as they are. They still describe how Tracker formats money.
A few things to notice:
- The expenses are a
map[string][]int: each category maps to a slice of amounts in cents. Food gets[350, 99], and Transport gets[1200]. - The tests compare maps with
maps.Equaland slices withslices.Equal. You’ll see in Review why!=doesn’t work for them. - Look at
Giftsin the last test. It’s in the map with a total of0.Travelisn’t in the map at all. The test says these must print differently, and that difference is what Must know #3 is about.
Run the tests:
go test ./...
# tracker [tracker.test]
./main_test.go:64:2: undefined: addExpense
./main_test.go:65:2: undefined: addExpense
./main_test.go:66:2: undefined: addExpense
./main_test.go:68:9: undefined: totalsByCategory
./main_test.go:77:9: undefined: sortedCategories
./main_test.go:95:10: undefined: describeCategory
FAIL tracker [build failed]
FAIL
There’s your to-do list: four functions.
Use the AI
First half: the AI as tutor
Start your assistant in the tracker folder and ask:
Explain Go maps and slices to a beginner. What does
map[string][]int mean? What happens when I look up a key that
isn't in a map? Don't write code for my project.
Follow up on anything unclear, especially what expenses[category] gives you when that category has no expenses yet. Then type these two functions at the end of main.go:
func addExpense(expenses map[string][]int, category string, cents int) {
expenses[category] = append(expenses[category], cents)
}
func totalsByCategory(expenses map[string][]int) map[string]int {
totals := make(map[string]int)
for category, amounts := range expenses {
totals[category] = total(amounts)
}
return totals
}
addExpense is short, but it uses three ideas at once. The first time you add a Food expense, expenses["Food"] doesn’t exist yet, so the lookup gives the zero value for a slice: nil. Appending to nil works fine and gives a slice with one item. Then the result is stored back under "Food". No special case is needed for “first expense in a category.”
totalsByCategory loops over a map. With a map, range gives you each key and its value. And it reuses total from Chapter 2, so code you’ve already tested does the adding.
Go has only one loop keyword, for, and it comes in three shapes:
for category, amounts := range expensesvisits every item in a map or slice. You’ll use this one most.for i := 0; i < 3; i++counts: start at 0, keep going whilei < 3, add 1 each time.for sum < 1000repeats while a condition is true, likewhilein other languages.
If the AI ever writes while, it’s thinking of another language. Go doesn’t have it. Ask your tutor for a tiny example of each shape if you want to see them run.
Run the tests again:
go test ./...
# tracker [tracker.test]
./main_test.go:77:9: undefined: sortedCategories
./main_test.go:95:10: undefined: describeCategory
FAIL tracker [build failed]
FAIL
Two items left on the list. These two are yours.
See for yourself: maps have no order
Before you write sortedCategories, see why you need it. Open a second terminal in the tracker folder and go to your practice folder from Chapter 2:
cd ../practice
Create order.go:
package main
import "fmt"
func main() {
totals := map[string]int{"Food": 449, "Fun": 1500, "Transport": 1200}
for category, cents := range totals {
fmt.Println(category, cents)
}
}
Run it five or six times with go run order.go. Sooner or later, the order changes. One run might print:
Transport 1200
Food 449
Fun 1500
Your runs will differ. That’s Must know #5. If Tracker printed straight from the map, your report would shuffle itself.
Second half: the AI as pair
Now the switch. First, tell your AI about its new job. Add this line to AGENTS.md:
When I ask for a review: list problems and suggestions with a one-line reason each, and don't rewrite my code.
Your first rule, “do not write or change code unless I ask,” still holds. The new rule says how to review.
Now write the last two functions yourself, at the end of main.go. Your tests tell you exactly what each one must do.
sortedCategories(totals map[string]int) []string returns the keys of totals, sorted by name. You’ll need:
- a
for ... rangeloop over the map (you only need the keys:for category := range totals) appendto collect each key into a sliceslices.Sortto sort the slice, which means adding"slices"to the imports inmain.go
describeCategory(totals map[string]int, category string) string returns "Food: 4.49" for a category in the map and "Travel: no expenses" for one that isn’t. You’ll need:
- the comma-ok lookup,
cents, ok := totals[category], whereokistrueonly if the key is in the map - an
ifto handle the missing case formatExpensefrom Chapter 2, which already formats"Food: 4.49"
To add "slices", change the top of main.go to:
import (
"fmt"
"slices"
)
Write, run go test ./..., read the errors, and repeat until you see ok. If you’re stuck, ask your AI to explain an error message or a concept, not to write the function.
Ask for a review
When your tests pass, ask for a review:
Review my sortedCategories and describeCategory functions in
main.go. List problems and suggestions, each with a one-line
reason. Don't rewrite my code; I'll decide what to change.
Every review is different, so the book can’t show you yours. But you’ll decide on each suggestion with the same three questions:
- Do I understand it? If you can’t explain the suggestion, you can’t keep it. That’s the one rule. Ask about it, or skip it for now.
- Does it fit this project? It must follow your rules:
AGENTS.md(Go 1.27, standard library only) and the book’s Must know points, like money in cents. - Do the tests still pass? Make one change at a time and run
go test ./...after each.
Here are example suggestions (not real AI output) and how the three questions sort them:
| Suggestion | Keep? | Why |
|---|---|---|
Create the slice with make([]string, 0, len(totals)) so it has room for every key |
Your call | It saves a little work as the slice grows. Keep it if you can explain what the len(totals) part does; otherwise skip it for now. |
| Add a comment above each function | Keep | Cheap, and it forces you to say what the function does, which is the Explain step in miniature. |
| Use a struct for expenses instead of a map of slices | Skip for now | Probably right, and Chapter 4 does exactly that. Changing it now would mean code you can’t explain yet. |
Use slices.Sorted(maps.Keys(totals)) |
Skip for now | It works in Go 1.27, but it uses iterators, which this book doesn’t cover. If you can’t explain it, don’t keep it. |
Import golang.org/x/exp/slices |
Reject | That’s an old location. The standard library has slices now, and your rules say standard library only. |
Notice that “skip for now” isn’t “the AI was wrong.” It means the suggestion isn’t right for you, today. That’s a judgment only you can make.
Compare with the book’s version
Here’s one version that passes the tests. Yours may look different, and that’s fine if your tests pass and you can explain every line:
func sortedCategories(totals map[string]int) []string {
var categories []string
for category := range totals {
categories = append(categories, category)
}
slices.Sort(categories)
return categories
}
func describeCategory(totals map[string]int, category string) string {
cents, ok := totals[category]
if !ok {
return category + ": no expenses"
}
return formatExpense(category, cents)
}
var categories []string starts as a nil slice, the zero value, and append grows it. That’s Must know #4 doing real work.
Print the report
Last, make main print the report from SPEC.md. Replace main with:
func main() {
fmt.Println(welcome())
expenses := make(map[string][]int)
addExpense(expenses, "Food", 350)
addExpense(expenses, "Transport", 1200)
addExpense(expenses, "Food", 99)
addExpense(expenses, "Fun", 1500)
totals := totalsByCategory(expenses)
for _, category := range sortedCategories(totals) {
fmt.Println(describeCategory(totals, category))
}
fmt.Println(describeCategory(totals, "Travel"))
}
Run it:
go run .
Welcome to Tracker. Let's see where your money goes.
Food: 4.49
Fun: 15.00
Transport: 12.00
Travel: no expenses
Run it as many times as you like. Thanks to sortedCategories, the order never changes.
Review
Let Go check first
gofmt -l .
go vet ./...
go test ./...
Silence, silence, ok.
Break it on purpose
Break 1: a nil map. In main, change expenses := make(map[string][]int) to var expenses map[string][]int, and run go run .:
Welcome to Tracker. Let's see where your money goes.
panic: assignment to entry in nil map
goroutine 1 [running]:
main.addExpense(...)
/home/you/tracker/main.go:50
main.main()
/home/you/tracker/main.go:12 +0x8c
exit status 2
Your folder path and the +0x8c part will differ. This is a panic: Go stopped your program while it was running. The compiler couldn’t catch it, because the code is valid Go. The first line says what went wrong, and the list below it shows where: addExpense, called from main. That’s Must know #4: a var map is nil, and writing to it crashes. Put make back.
Break 2: forget the ok. In describeCategory, replace the first four lines of the body with cents := totals[category], and run go test ./...:
--- FAIL: TestDescribeCategory (0.00s)
main_test.go:97: describeCategory("Travel") = "Travel: 0.00", want "Travel: no expenses"
FAIL
FAIL tracker 0.001s
FAIL
Without ok, a missing category looks exactly like a category that totals zero, because a missing key gives the zero value. Your Travel row caught it. The Gifts row, which still passes, shows why: zero and missing look the same without ok. Put the ok check back.
Check it yourself
Be SURE you can explain it, including every suggestion you kept.
Explain
Say it in your own words
Write a few sentences about how Tracker records and reports expenses. Include one sentence about a review suggestion: one you kept or skipped, and why. For example:
Let the AI quiz you
Ask me two questions about maps, slices or zero values, using my
code in main.go. Wait for my answers before you tell me if I'm right.
Write a Learned: line in your commit
git add .
git commit -m "Record expenses and total them by category" -m "Learned: a missing map key gives the zero value, so use the comma-ok form to tell missing from zero."
Update AGENTS.md if something surprised you
You already added the review rule. If the AI rewrote your code anyway, or suggested something that broke your rules, add a line about it now. Commit the change.
Practice (optional)
Add a count of expenses per category to Tracker’s report. After the totals, go run . should also print:
Food: 2 expenses
Fun: 1 expense
Transport: 1 expense
Note “1 expense,” not “1 expenses.” That’s a job for if.
Go around the whole SURE loop, in pair mode: add the sentence to SPEC.md, write a test first, write the code yourself, then ask the AI for a review and decide on each suggestion. Hint: len tells you how many items a slice has.
Tried it? Compare with the worked answer for Chapter 3.
What you’ve done
You used slices and maps for real, met zero values in three places (a missing key, a nil slice and a nil map), and saw your first panic. Most importantly, you wrote code yourself and treated the AI’s review as suggestions to judge, not orders to follow.
In Chapter 4, Tracker gets a proper Expense type, the struct the AI kept suggesting, and saves your expenses to a file, so they’re still there tomorrow. Saving to a file means things can go wrong, so you’ll also learn how Go handles errors.