Learn Go with AI · Free online book
Chapter 4: Modeling Data and Handling Errors
In short: Chapter 4 gives Tracker a proper shape with a struct and methods, and makes it remember your expenses in a JSON file. Because saving to a file can fail, you also learn Go's error handling: returning errors, wrapping them with %w and never ignoring them.
Close Tracker, and your expenses are gone. Every run starts from the same four hard-coded amounts. A tracker that forgets everything isn’t much of a tracker.
In this chapter, Tracker learns to remember. You’ll give expenses a proper shape with a struct, which is the suggestion the AI kept making in Chapter 3. You’ll give Tracker methods that add, total, save and load expenses. And because saving to a file is the first thing in this book that can fail for reasons outside your code (a missing folder, a broken file), you’ll learn how Go handles errors.
The AI is your pair for this whole chapter. The book gives you the first part of the new code. Then you write the rest yourself, ask the AI for a review, and decide what to keep, using the same three questions as Chapter 3. It’s the same SURE loop, with more of it in your hands.
Mission
By the end of this chapter, you’ll have:
- An
Expensestruct and aTrackertype with methods - Tracker saving your expenses to
expenses.jsonand loading them on the next run - A command to add expenses:
go run . add Food 350 - Clear error messages for bad input, instead of crashes or silent mistakes
- A commit with a
Learned:line
Must know
- A struct groups named fields into one type.
type Expense struct { Category string; Cents int }describes every expense. Fields that start with a capital letter are exported, andencoding/jsononly sees exported fields. (Chapter 5 covers exported names properly.) - A method is a function attached to a type.
func (tr *Tracker) Add(...)is a method onTracker. You call it with a dot:tracker.Add("Food", 350). - A pointer lets a function change the original instead of a copy.
*Trackermeans “a pointer to a Tracker,” and&xgives you a pointer tox. A method that changes its value needs a pointer receiver,(tr *Tracker). Otherwise it changes a copy, and the change disappears. - Errors are values. A function that can fail returns an
erroras its last result.nilmeans it worked. You check every error:if err != nil { ... }. - Wrap errors to add context.
fmt.Errorf("save expenses: %w", err)adds what you were doing to the error. Later,errors.Is(err, target)can still look inside the wrapping. The%wis what makes that work.
Specify
Replace SPEC.md with the new behavior:
1. `go run .` prints the welcome sentence, then one line per
category with its total, sorted by name. With no expenses,
it prints "No expenses yet." under the welcome sentence.
2. `go run . add Food 350` adds an expense of 3.50 to Food,
saves it, and prints: Added Food: 3.50
3. Expenses are saved in expenses.json and are still there on
the next run.
4. If expenses.json doesn't exist yet, Tracker starts empty.
That's not an error.
5. An amount that isn't a whole number, or is zero or less, gives
a clear error, and nothing is saved.
Amounts are still whole cents, so 350 means 3.50. A friendlier input like 3.50 would need its own parsing code, and that can wait.
The new code will live in a new file, tracker.go, so its tests go in a new file too. Create tracker_test.go next to main.go:
package main
import (
"errors"
"maps"
"os"
"path/filepath"
"slices"
"testing"
)
func TestTrackerAdd(t *testing.T) {
tests := []struct {
name string
category string
cents int
wantErr error
wantLen int
}{
{"valid", "Food", 350, nil, 1},
{"zero", "Food", 0, ErrInvalidAmount, 0},
{"negative", "Food", -100, ErrInvalidAmount, 0},
}
for _, tt := range tests {
var tr Tracker
err := tr.Add(tt.category, tt.cents)
if !errors.Is(err, tt.wantErr) {
t.Errorf("%s: Add() error = %v, want %v", tt.name, err, tt.wantErr)
}
if len(tr.expenses) != tt.wantLen {
t.Errorf("%s: %d expenses after Add, want %d", tt.name, len(tr.expenses), tt.wantLen)
}
}
}
func TestTrackerTotals(t *testing.T) {
tr := Tracker{expenses: []Expense{
{Category: "Food", Cents: 350},
{Category: "Transport", Cents: 1200},
{Category: "Food", Cents: 99},
}}
got := tr.Totals()
want := map[string]int{"Food": 449, "Transport": 1200}
if !maps.Equal(got, want) {
t.Errorf("Totals() = %v, want %v", got, want)
}
}
func TestSaveAndLoad(t *testing.T) {
path := filepath.Join(t.TempDir(), "expenses.json")
saved := Tracker{expenses: []Expense{
{Category: "Food", Cents: 350},
{Category: "Fun", Cents: 1500},
}}
if err := saved.Save(path); err != nil {
t.Fatalf("Save() error = %v", err)
}
loaded, err := Load(path)
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if !slices.Equal(loaded.expenses, saved.expenses) {
t.Errorf("loaded %v, want %v", loaded.expenses, saved.expenses)
}
}
func TestLoadMissingFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "missing.json")
tr, err := Load(path)
if err != nil {
t.Fatalf("Load() error = %v, want nil", err)
}
if len(tr.expenses) != 0 {
t.Errorf("Load() has %d expenses, want 0", len(tr.expenses))
}
}
func TestLoadBrokenFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "expenses.json")
if err := os.WriteFile(path, []byte("not json"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil {
t.Error("Load() error = nil, want an error for a broken file")
}
}
Three new testing tools appear here:
errors.Is(err, tt.wantErr)checks whether an error is, or wraps, a specific error. WhenwantErrisnil, it checks that there was no error at all.t.TempDir()gives each test a fresh, empty folder that Go deletes afterwards, so tests never touch your realexpenses.json.t.Fatalfreports a failure and stops that test immediately. Use it when there’s no point going on: ifSavefailed, there’s nothing toLoad.
Notice that TestTrackerTotals builds its Tracker directly with the expenses inside, instead of calling Add. That keeps it from ignoring Add’s errors, and ignoring errors is exactly what this chapter teaches you not to do.
Run the tests:
go test ./...
# tracker [tracker.test]
./tracker_test.go:21:23: undefined: ErrInvalidAmount
./tracker_test.go:22:30: undefined: ErrInvalidAmount
./tracker_test.go:25:10: undefined: Tracker
./tracker_test.go:37:8: undefined: Tracker
./tracker_test.go:37:28: undefined: Expense
./tracker_test.go:51:11: undefined: Tracker
./tracker_test.go:51:31: undefined: Expense
./tracker_test.go:58:17: undefined: Load
./tracker_test.go:69:13: undefined: Load
./tracker_test.go:83:15: undefined: Load
./tracker_test.go:83:15: too many errors
FAIL tracker [build failed]
FAIL
“Too many errors” means Go stopped listing after ten. Your to-do list is longer than it shows.
Use the AI
Learn the new ideas
Your AI is a pair now, but you can always ask it to explain. Start with:
Explain Go structs, methods and pointer receivers to a beginner.
Why would a method need (tr *Tracker) instead of (tr Tracker)?
Don't write code for my project.
Then:
How do errors work in Go? What does fmt.Errorf with %w do, and how
does errors.Is use it? Use a small example that isn't about money.
Type the first part
Create tracker.go and type this:
package main
import (
"errors"
"fmt"
)
// Expense is one thing you spent money on.
type Expense struct {
Category string `json:"category"`
Cents int `json:"cents"`
}
// Tracker holds all your expenses.
type Tracker struct {
expenses []Expense
}
// ErrInvalidAmount means an expense amount was zero or negative.
var ErrInvalidAmount = errors.New("amount must be more than zero")
// Add records one expense.
func (tr *Tracker) Add(category string, cents int) error {
if cents <= 0 {
return fmt.Errorf("add %q: %w", category, ErrInvalidAmount)
}
tr.expenses = append(tr.expenses, Expense{Category: category, Cents: cents})
return nil
}
Things to notice:
- The text after each field, like
`json:"category"`, is a struct tag. It tellsencoding/jsonto write the field as"category"in the file instead of"Category". Expense{Category: category, Cents: cents}inAddbuilds an expense with named fields: each field’s name, a colon, then its value. You read or set a field with a dot: ifeis anExpense,e.Categoryis its category, ande.Cents = 500changes its amount.- Any field you leave out gets its zero value, the rule from Chapter 3:
Expense{Category: "Food"}hasCentsset to0, andvar e ExpensehasCategory""andCents0. expensesstarts with a lowercase letter, so it’s private to this package. Other code goes throughAddand the other methods rather than touching the slice directly.ErrInvalidAmountis a sentinel error: a named error that callers can check for witherrors.Is.Addwraps it with the category, so the message says what went wrong and where.Addreturnsnilwhen everything worked. Every path through a function that returnserrorends with an error ornil.
Run go test ./... again:
# tracker [tracker.test]
./tracker_test.go:42:12: tr.Totals undefined (type Tracker has no field or method Totals)
./tracker_test.go:55:18: saved.Save undefined (type Tracker has no field or method Save)
./tracker_test.go:58:17: undefined: Load
./tracker_test.go:69:13: undefined: Load
./tracker_test.go:83:15: undefined: Load
FAIL tracker [build failed]
FAIL
Three items left: Totals, Save and Load. These are yours.
Your turn: Totals, Save and Load
Add these to the end of tracker.go. Your tests say exactly what each must do.
func (tr *Tracker) Totals() map[string]int returns the total for each category. Loop over tr.expenses and add each expense’s Cents to its category in a new map. You did almost the same thing in Chapter 3.
func (tr *Tracker) Save(path string) error writes all expenses to a file:
json.MarshalIndent(tr.expenses, "", " ")turns the slice into JSON text, indented with two spaces. It returns the text and an error.os.WriteFile(path, data, 0o644)writes the text to the file.0o644sets the file’s permissions: you can read and write it, and others can only read it.- Check both errors, and wrap each with
fmt.Errorf("save expenses: %w", err).
func Load(path string) (*Tracker, error) is a plain function, not a method, because there’s no Tracker yet when you load one. It reads the file and returns a new Tracker:
os.ReadFile(path)returns the file’s contents and an error.- If the file doesn’t exist,
errors.Is(err, os.ErrNotExist)is true. That’s not a failure: return an empty&Tracker{}andnil. - Any other error: return
niland the error wrapped with"load expenses: %w". json.Unmarshal(data, &tr.expenses)fills the slice from the JSON text. It needs a pointer (&) so it can change the slice. Check its error too.
You’ll need two more imports in tracker.go: "encoding/json" and "os". Then write, run go test ./..., read the errors, and repeat until you see ok. If you’re stuck, ask the AI to explain an error message, not to write the method.
Ask for a review
Review the Totals, Save and Load methods in tracker.go. List
problems and suggestions, each with a one-line reason. Don't
rewrite my code; I'll decide what to change.
Decide on each suggestion with the same three questions as Chapter 3:
- Do I understand it? If you can’t explain it, you can’t keep it.
- 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? One change at a time, then
go test ./....
Here are example suggestions (not real AI output) and how the questions sort them:
| Suggestion | Keep? | Why |
|---|---|---|
| Write to a temporary file, then rename it, so a crash can’t leave a half-written file | Your call | A real improvement. Keep it if you can explain why the rename helps; otherwise note it for later. |
Call log.Fatal(err) inside Load instead of returning the error |
Reject | It would end the whole program from deep inside. Functions return errors; only main decides to stop. |
Use json.NewEncoder with an open file instead of MarshalIndent |
Skip for now | It works, but it brings in opening and closing files. Same result, more to explain. |
Store amounts as float64 in the JSON, like "amount": 3.5 |
Reject | Money is whole cents. That’s a Must know point, not a style choice. |
Compare with the book’s version
Here’s one version that passes the tests. Yours may differ; that’s fine if your tests pass and you can explain every line.
// Totals returns the total in cents for each category.
func (tr *Tracker) Totals() map[string]int {
totals := make(map[string]int)
for _, e := range tr.expenses {
totals[e.Category] += e.Cents
}
return totals
}
// Save writes all expenses to the JSON file at path.
func (tr *Tracker) Save(path string) error {
data, err := json.MarshalIndent(tr.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
}
// Load reads expenses from the JSON file at path.
// A missing file means there are no expenses yet.
func Load(path string) (*Tracker, error) {
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return &Tracker{}, nil
}
if err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
tr := &Tracker{}
if err := json.Unmarshal(data, &tr.expenses); err != nil {
return nil, fmt.Errorf("load expenses: %w", err)
}
return tr, nil
}
if err := os.WriteFile(...); err != nil is a common Go shape: the if runs a statement first, then checks the condition. The err it creates only exists inside that if.
Connect Tracker to main
The old map-based code is replaced, so remove it:
- In
main.go, delete theaddExpenseandtotalsByCategoryfunctions.Trackerdoes their jobs now. - In
main_test.go, deleteTestTotalsByCategory, and remove"maps"from its imports. Nothing else in that file usesmaps, and Go refuses unused imports.
Then, in main.go, replace the import block and the whole main function with this:
import (
"errors"
"fmt"
"os"
"slices"
"strconv"
)
const dataFile = "expenses.json"
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}
func run(args []string) error {
tracker, err := Load(dataFile)
if err != nil {
return err
}
if len(args) == 0 {
fmt.Println(welcome())
totals := tracker.Totals()
if len(totals) == 0 {
fmt.Println("No expenses yet.")
}
for _, category := range sortedCategories(totals) {
fmt.Println(describeCategory(totals, category))
}
return nil
}
if len(args) == 3 && args[0] == "add" {
category := args[1]
cents, err := strconv.Atoi(args[2])
if err != nil {
return fmt.Errorf("amount must be whole cents: %w", err)
}
if err := tracker.Add(category, cents); err != nil {
return err
}
if err := tracker.Save(dataFile); err != nil {
return err
}
fmt.Println("Added", formatExpense(category, cents))
return nil
}
return errors.New("usage: go run . [add CATEGORY CENTS]")
}
This is the pattern for every error in a Go program. run does the work and returns any error it meets, and only main decides what to do about it: print it and stop. os.Args holds the words typed after the program’s name, strconv.Atoi turns text like "350" into the number 350, and fmt.Fprintln(os.Stderr, ...) prints to the terminal’s error output.
Now try it. Start with no data file:
go run .
Welcome to Tracker. Let's see where your money goes.
No expenses yet.
Add the expenses from Chapter 3, one command at a time:
go run . add Food 350
go run . add Transport 1200
go run . add Food 99
go run . add Fun 1500
Added Food: 3.50
Added Transport: 12.00
Added Food: 0.99
Added Fun: 15.00
Now run the report. Every go run is a fresh program, so these totals came from the file:
go run .
Welcome to Tracker. Let's see where your money goes.
Food: 4.49
Fun: 15.00
Transport: 12.00
Open expenses.json in your editor. It’s plain text you can read:
[
{
"category": "Food",
"cents": 350
},
{
"category": "Transport",
"cents": 1200
},
{
"category": "Food",
"cents": 99
},
{
"category": "Fun",
"cents": 1500
}
]
Remember “What not to give the AI” from Chapter 1: your assistant can read this file. Keep using made-up expenses.
Finally, try some bad input:
go run . add Food 3.50
go run . add Food 0
go run . add
Error: amount must be whole cents: strconv.Atoi: parsing "3.50": invalid syntax
exit status 1
Error: add "Food": amount must be more than zero
exit status 1
Error: usage: go run . [add CATEGORY CENTS]
exit status 1
Read the first message from left to right. Each : is one layer of wrapping: your context first, then strconv’s own error. That’s what %w buys you. exit status 1 comes from go run, telling you the program stopped with an error.
Review
Let Go check first
gofmt -l .
go vet ./...
go test ./...
Silence, silence, ok.
Break it on purpose
Break 1: lose the pointer. In tracker.go, change func (tr *Tracker) Add to func (tr Tracker) Add, removing one *. It compiles, and go vet stays silent. Now run go test ./...:
--- FAIL: TestTrackerAdd (0.00s)
tracker_test.go:31: valid: 0 expenses after Add, want 1
FAIL
FAIL tracker 0.003s
FAIL
Without the pointer, Add appends to a copy of the Tracker, and the copy disappears when Add returns. No error, no crash, just a lost expense. Only the test caught it, because it checks the count. Put the * back.
Break 2: %v instead of %w. In Add, change %w to %v and run go test ./...:
--- FAIL: TestTrackerAdd (0.00s)
tracker_test.go:28: zero: Add() error = add "Food": amount must be more than zero, want amount must be more than zero
tracker_test.go:28: negative: Add() error = add "Food": amount must be more than zero, want amount must be more than zero
FAIL
FAIL tracker 0.004s
FAIL
The message looks identical, but errors.Is can’t find ErrInvalidAmount inside it anymore. %v copies the error’s text; %w keeps the error itself inside. Put %w back.
Check it yourself
Be SURE you can explain it, including the if err := ...; err != nil lines.
Explain
Say it in your own words
Write a few sentences about how Tracker remembers expenses and handles mistakes. For example:
Let the AI quiz you
Ask me two questions about structs, pointers or errors, using my
code in tracker.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 "Save and load expenses with a Tracker type" -m "Learned: a method needs a pointer receiver to change its value, or it only changes a copy."
expenses.json is included in this commit. Since your expenses are made up, that’s fine. In a real project, you’d usually keep personal data out of Git.
Update AGENTS.md if something surprised you
Did the AI’s review suggest log.Fatal, float64 or ignoring an error? Add a rule, such as:
Always check and wrap errors with fmt.Errorf and %w; never ignore them with _.
Commit the change.
Practice (optional)
Here’s a short program an AI might write to back up expenses. It compiles, go vet is silent, and it even prints a cheerful message. It also has four ignored errors. Save it as ignored.go in your practice folder and run it with go run ignored.go:
package main
import (
"encoding/json"
"fmt"
"os"
)
type Expense struct {
Category string `json:"category"`
Cents int `json:"cents"`
}
func save(path string, expenses []Expense) {
data, _ := json.MarshalIndent(expenses, "", " ")
os.WriteFile(path, data, 0o644)
}
func load(path string) []Expense {
data, _ := os.ReadFile(path)
var expenses []Expense
json.Unmarshal(data, &expenses)
return expenses
}
func main() {
expenses := []Expense{
{Category: "Food", Cents: 350},
{Category: "Fun", Cents: 1500},
}
save("backup/expenses.json", expenses)
fmt.Println("Saved", len(expenses), "expenses")
loaded := load("backup/expenses.json")
fmt.Println("Loaded", len(loaded), "expenses")
}
It prints:
Saved 2 expenses
Loaded 0 expenses
Two expenses saved, zero loaded, and no error anywhere. The backup folder doesn’t exist, so the save failed, but nothing told you.
Your job: find all four ignored errors. Then make save and load return errors, wrapped with %w, and make main print the error and stop, the way Tracker’s main does. When you’re done, running it should print an error that mentions backup/expenses.json and says the file or folder doesn’t exist (the exact wording differs on Windows). Use the SURE loop, and ask the AI for a review when your version works.
Tried it? Compare with the worked answer for Chapter 4.
What you’ve done
Tracker now has a real data model, remembers your expenses between runs, and turns bad input into clear messages instead of crashes or silent mistakes. You wrote three methods yourself, used pointers and saw what happens without them, and learned why %w matters even when the message looks the same.
Tracker is getting crowded, though: everything lives in package main. In Chapter 5, you’ll split it into packages and give storage an interface, so Tracker can save to a file or keep everything in memory. That’s also where the AI’s role shifts again: from pair to implementer.