Learn Go with AI · Free online book
Practice answers
In short: Worked answers to the optional Practice exercise at the end of each chapter, from printing today's date to finding a data race. Try each exercise first; every answer was run on Go 1.27.4.
These are worked answers to the optional Practice exercise at the end of each chapter. Try the exercise first: the struggle is where the learning happens. When you compare, remember that your code can look different and still be right, as long as your tests pass and you can explain every line.
Every answer below was run on Go 1.27.4 with gofmt -l ., go vet ./... and go test ./... (and go test -race ./... for Chapters 6 and 7).
Chapter 1: print today’s date
Back to the Chapter 1 exercise
First, the spec. Add a second sentence to SPEC.md:
It then prints "Today is " and today's date as YYYY-MM-DD, for example:
`Today is 2026-11-24`
Then main.go:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Welcome to Tracker. Let's see where your money goes.")
fmt.Println("Today is " + time.Now().Format("2006-01-02"))
}
Go doesn’t format dates with codes like YYYY or %Y. It uses one reference time, Mon Jan 2 15:04:05 MST 2006, and you write the layout by showing how that exact moment would look. 2006 means the year, 01 the month and 02 the day, so "2006-01-02" prints 2026-11-24. If you’d written "2006-02-01", Go would print the day before the month. That’s the trap AI-written date code falls into most often.
Explain it: why can’t the test for this line say exactly what to print? (Hint: what’s different tomorrow?)
Chapter 2: five broken programs
Back to the Chapter 2 exercise
fix1.go: invalid operation: name + ": " + cents (mismatched types string and int). Go won’t add a number to a string. Let fmt.Println print both, and it puts a space between them:
package main
import "fmt"
func main() {
name := "Coffee"
cents := 350
fmt.Println(name+":", cents)
}
strconv.Itoa(cents) also works: it turns 350 into "350". string(cents) doesn’t: it turns 350 into the character with code 350, Ş. go vet warns about it, as the box in the chapter says.
fix2.go: declared and not used: count. Go refuses to compile a local variable you never use. Delete it:
package main
import "fmt"
func main() {
amount := 350
fmt.Println("Amount:", amount)
}
fix3.go: assignment mismatch: 1 variable but splitCents returns 2 values. A function that returns two values needs two names on the left. Use _ for the one you don’t need:
package main
import "fmt"
func splitCents(cents int) (int, int) {
return cents / 100, cents % 100
}
func main() {
whole, _ := splitCents(1649)
fmt.Println("Whole units:", whole)
}
fix4.go: two errors, declared and not used: result and missing return. The function promises an int but never returns one. Returning result fixes both, because now result is used:
package main
import "fmt"
func double(cents int) int {
result := cents * 2
return result
}
func main() {
fmt.Println(double(350))
}
return cents * 2 on its own line also works.
fix5.go: no new variables on left side of :=. := makes a new variable, and total already exists. To change it, use =:
package main
import "fmt"
func main() {
total := 350
total = total + 1200
fmt.Println("Total:", total)
}
Chapter 3: count expenses per category
Back to the Chapter 3 exercise
Specify first. Add sentence 5 to SPEC.md:
5. After the totals, it prints how many expenses each category has,
sorted by name, with "expense" for one and "expenses" for more:
Food: 2 expenses
Fun: 1 expense
Transport: 1 expense
Then a test, at the end of main_test.go. It has a row for “1 expense” and one for “2 expenses”, because that difference is the whole point of the exercise:
func TestDescribeCount(t *testing.T) {
expenses := make(map[string][]int)
addExpense(expenses, "Food", 350)
addExpense(expenses, "Food", 99)
addExpense(expenses, "Fun", 1500)
tests := []struct {
category string
want string
}{
{"Food", "Food: 2 expenses"},
{"Fun", "Fun: 1 expense"},
}
for _, tt := range tests {
got := describeCount(expenses, tt.category)
if got != tt.want {
t.Errorf("describeCount(%q) = %q, want %q", tt.category, got, tt.want)
}
}
}
Run go test ./... and watch it fail with undefined: describeCount. Then the function, at the end of main.go:
func describeCount(expenses map[string][]int, category string) string {
count := len(expenses[category])
if count == 1 {
return fmt.Sprintf("%s: %d expense", category, count)
}
return fmt.Sprintf("%s: %d expenses", category, count)
}
len(expenses[category]) is the number of amounts in that category’s slice. For a category that isn’t in the map, the lookup gives a nil slice, and len of nil is 0, so this never crashes.
Last, print the counts at the end of main, reusing sortedCategories so the order stays fixed:
for _, category := range sortedCategories(totals) {
fmt.Println(describeCount(expenses, category))
}
go run . now ends with:
Food: 2 expenses
Fun: 1 expense
Transport: 1 expense
A review suggestion you might get: “use if count != 1” so that 0 expenses also reads well. Keep it if you can explain it.
Chapter 4: find the four ignored errors
Back to the Chapter 4 exercise
The four ignored errors are:
json.MarshalIndentinsave(data, _ :=)os.WriteFileinsave(its result isn’t used at all)os.ReadFileinload(data, _ :=)json.Unmarshalinload(its result isn’t used at all)
Here’s one fixed version. save and load return wrapped errors, and main prints the error and stops, the way Tracker’s main does with run:
package main
import (
"encoding/json"
"fmt"
"os"
)
type Expense struct {
Category string `json:"category"`
Cents int `json:"cents"`
}
func save(path string, expenses []Expense) error {
data, err := json.MarshalIndent(expenses, "", " ")
if err != nil {
return fmt.Errorf("save expenses: %w", err)
}
if err := os.WriteFile(path, data, 0o644); err != nil {
return fmt.Errorf("save expenses: %w", err)
}
return nil
}
func load(path string) ([]Expense, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
return expenses, nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}
func run() error {
expenses := []Expense{
{Category: "Food", Cents: 350},
{Category: "Fun", Cents: 1500},
}
if err := save("backup/expenses.json", expenses); err != nil {
return err
}
fmt.Println("Saved", len(expenses), "expenses")
loaded, err := load("backup/expenses.json")
if err != nil {
return err
}
fmt.Println("Loaded", len(loaded), "expenses")
return nil
}
Run it with no backup folder:
Error: save expenses: open backup/expenses.json: no such file or directory
exit status 1
On Windows, the last part says The system cannot find the path specified. Make the folder (mkdir backup) and run it again, and it prints Saved 2 expenses and Loaded 2 expenses.
The wrapping is what makes that message useful: save expenses: says what you were doing, and the error from os.WriteFile inside it says what went wrong and with which file.
Chapter 5: test whether the AI follows your rules
Back to the Chapter 5 exercise
This exercise is about the AI, so there’s no single answer: what matters is whether your AI followed your three rules. Here’s what a correct result looks like, so you have something to check against.
The test, in ledger/ledger_test.go, committed before you ask the AI:
func TestTrackerCount(t *testing.T) {
var empty Tracker
if got := empty.Count(); got != 0 {
t.Errorf("empty Count() = %d, want 0", got)
}
var tr Tracker
if err := tr.Add("Food", 350); err != nil {
t.Fatalf("Add() error = %v", err)
}
if err := tr.Add("Fun", 1500); err != nil {
t.Fatalf("Add() error = %v", err)
}
if got := tr.Count(); got != 2 {
t.Errorf("Count() = %d, want 2", got)
}
}
The method the AI should write, in ledger/ledger.go:
// Count returns how many expenses the Tracker holds.
func (tr *Tracker) Count() int {
return len(tr.expenses)
}
Check it against your rules:
- Doc comment: it starts with the name,
Count. - Test files:
git statusshows onlyledger/ledger.gochanged. If a_test.gofile is listed, the AI broke the rule:git restoreit and ask again. - Error messages:
Countcan’t fail, so this rule isn’t tested by this feature. To test it, specify a feature that returns an error, and check that its message starts with a lowercase letter and has no full stop at the end.
If a rule keeps failing, make it more specific. “Never edit files ending in _test.go unless I ask” works better than “don’t touch the tests,” because the AI can check it against a file name.
Chapter 6: GET /totals/{category}
Back to the Chapter 6 exercise
The two sentences go at the end of SPEC.md, as the exercise shows. Then the tests, at the end of api/api_test.go:
func TestCategoryTotal(t *testing.T) {
h := newTestHandler(t, &ledger.MemoryStorage{})
add(t, h, `{"category":"Food","cents":350}`)
add(t, h, `{"category":"Transport","cents":1200}`)
add(t, h, `{"category":"Food","cents":99}`)
rec := send(h, "GET", "/totals/Food", "")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
want := `{"category":"Food","cents":449}` + "\n"
if got := rec.Body.String(); got != want {
t.Errorf("body = %q, want %q", got, want)
}
}
func TestCategoryTotalNotFound(t *testing.T) {
h := newTestHandler(t, &ledger.MemoryStorage{})
add(t, h, `{"category":"Food","cents":350}`)
rec := send(h, "GET", "/totals/Travel", "")
if rec.Code != http.StatusNotFound {
t.Errorf("status = %d, want %d", rec.Code, http.StatusNotFound)
}
}
Run go test ./... before writing any handler:
--- FAIL: TestCategoryTotal (0.00s)
api_test.go:118: status = 404, want 200
FAIL
Your line number may differ. Notice that TestCategoryTotalNotFound already passes: with no handler for the path, the mux answers 404 for every category. A test that passes before you write the code isn’t proving much on its own. It’s the Food test that forces the real work, and the two tests together pin down the difference.
If you went further and had the AI implement it, a good handler in NewHandler looks like this:
mux.HandleFunc("GET /totals/{category}", func(w http.ResponseWriter, r *http.Request) {
category := r.PathValue("category")
cents, ok := tr.Totals()[category]
if !ok {
http.Error(w, "no expenses in "+category, http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, ledger.Expense{Category: category, Cents: cents})
})
Review points: it uses the comma-ok lookup from Chapter 3, so a missing category is a 404 and not a total of 0. It reuses ledger.Expense, whose JSON tags already give {"category":"Food","cents":449}. And it reuses writeJSON, so the Content-Type header is set the same way as everywhere else.
Chapter 7: find the data race
Back to the Chapter 7 exercise
go test -race ./... reports a race between:
Add, writings.totalon thes.total += centsline (line 15 ofspending.go), andTotal, readings.totalon thereturn s.totalline (line 21).
Your report may list them the other way round. Add holds the lock, but Total doesn’t, so one goroutine can read the total while another is writing it. A mutex only protects the data if every access takes the lock, reads included.
The fix is two lines in Total:
// Total returns the total so far.
func (s *Spending) Total() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.total
}
Run go test -race ./... again, a few times:
ok racy 1.013s
Why did the plain test pass every time? The race detector looks at how the goroutines access memory, not at the answer. On most runs the timing works out and the total is right, which is exactly why a race can hide in a passing test.