Learn Go with AI · Free online book

Chapter 2: Your First Program and Your First Test

In short: Chapter 2 turns your spec into a Go test, so Go checks your work instead of your eyes. You write your first functions, total a list of amounts with a table-driven test, and learn why Tracker stores money in whole cents instead of float64.

In Chapter 1, you checked “done” with your own eyes: you ran the program and compared its output with the sentence in SPEC.md. That works for one line. It doesn’t work for a hundred.

In this chapter, Go starts checking for you. You’ll turn your SPEC.md sentence into a test, a small piece of code that runs your program’s code and says “pass” or “fail.” Then Tracker learns its first real job: printing an expense and adding up a list of amounts.

Tests matter even more when AI is involved. The AI can say “Sure!” and hand you code that looks right. A test doesn’t care how confident anyone sounds. It either passes or it doesn’t.

It’s the same SURE loop as Chapter 1, but this time Specify ends with tests. The AI is still your tutor: it explains; you type.

Mission

By the end of this chapter, you’ll have:

You’ll also see why Tracker stores money in a way that might surprise you.

Must know

These facts come from the book. If the AI says something different, the AI is wrong.

  1. Every value has a type. 350 is an int (a whole number), "Coffee" is a string (text), 3.5 is a float64 (a number with a decimal point) and true is a bool. Go checks types before your program runs, and it won’t mix them: adding a string to an int doesn’t compile.
  2. := creates a variable inside a function. cents := 350 creates cents and gives it the type of its value, int. Like imports, a variable you create and never use stops your program from compiling.
  3. Tracker stores money as whole cents in an int. Coffee for 3.50 is stored as 350. A float64 can’t hold most decimal amounts exactly, and in money, small errors add up.
  4. A function says what it takes and what it gives back. func total(amounts []int) int takes a list of ints and returns one int. A Go function can return more than one value.
  5. Tests live in files ending in _test.go. Each test is a function whose name starts with Test. You run them all with go test ./....

Specify

You’ll specify three things this time. Open SPEC.md and make it say:

1. `go run .` prints exactly:
   Welcome to Tracker. Let's see where your money goes.
2. Then it prints one expense, Coffee for 3.50, as:
   Coffee: 3.50
3. Then it prints the total of 3.50, 12.00 and 0.99 as:
   Total: 16.49

Now comes the new part. Instead of checking these sentences by eye, you’ll write them as tests, before writing the code that makes them pass. That might sound backwards, but it’s the most reliable way to know what “done” means: Go tells you.

Create a file named main_test.go next to main.go, and type this:

package main

import "testing"

func TestWelcome(t *testing.T) {
    want := "Welcome to Tracker. Let's see where your money goes."
    got := welcome()
    if got != want {
        t.Errorf("welcome() = %q, want %q", got, want)
    }
}

func TestFormatExpense(t *testing.T) {
    want := "Coffee: 3.50"
    got := formatExpense("Coffee", 350)
    if got != want {
        t.Errorf("formatExpense() = %q, want %q", got, want)
    }
}

func TestFormatAmount(t *testing.T) {
    tests := []struct {
        cents int
        want  string
    }{
        {350, "3.50"},
        {1200, "12.00"},
        {99, "0.99"},
        {5, "0.05"},
        {0, "0.00"},
    }
    for _, tt := range tests {
        got := formatAmount(tt.cents)
        if got != tt.want {
            t.Errorf("formatAmount(%d) = %q, want %q", tt.cents, got, tt.want)
        }
    }
}

func TestTotal(t *testing.T) {
    tests := []struct {
        name    string
        amounts []int
        want    int
    }{
        {"no expenses", []int{}, 0},
        {"one expense", []int{350}, 350},
        {"three expenses", []int{350, 1200, 99}, 1649},
    }
    for _, tt := range tests {
        got := total(tt.amounts)
        if got != tt.want {
            t.Errorf("%s: total(%v) = %d, want %d", tt.name, tt.amounts, got, tt.want)
        }
    }
}

Look at TestWelcome first. Its want is your SPEC.md sentence from Chapter 1, word for word. That’s the promise from the last chapter: your spec is now code that Go can check.

Every test in this book has the same three-part shape:

%q prints text with quotes around it, so a stray space at the end of a sentence becomes visible. want and got aren’t special words in Go; they’re just names that Go programmers use so that every test reads the same way.

The last two tests are table-driven tests. Instead of writing one test per case, you write a table of cases (inputs and the output you want) and loop over it. Adding a case is one new line. Every row is there for a reason: 5 checks that five cents prints as 0.05, not 0.5, and the empty list checks that “no expenses” totals zero.

Don’t worry about understanding every symbol yet. That’s what the next step is for.

Run the tests now, before any of the code exists:

go test ./...
# tracker [tracker.test]
./main_test.go:7:9: undefined: welcome
./main_test.go:15:9: undefined: formatExpense
./main_test.go:33:10: undefined: formatAmount
./main_test.go:51:10: undefined: total
FAIL    tracker [build failed]
FAIL

That’s exactly right. Each line names a function your tests expect and your program doesn’t have yet. This list is now your to-do list.

Seeing your tests fail first isn’t wasted time. It proves two things: the tests really run, and they really check something. A test that has never failed might be passing for the wrong reason. This rhythm of failing test, then code, then passing test is how you’ll work for the rest of the book.

Use the AI

Start your assistant in the tracker folder. Your AI is still a tutor, so first, ask it to explain the tests you typed:

Explain main_test.go line by line, as if I've never seen a Go test.
Don't write any code for main.go; I'll write it myself.

Read the answer slowly, with the file open next to it. Ask about anything that’s still unclear, such as %q, t.Errorf or the []struct{...} table. You’ll learn more about that table shape in Chapter 4; for now, think of each {...} line as one row.

Next, learn what you need to write the code:

How do I write a Go function that takes parameters and returns a
value? How can a function return two values? Use an example that
isn't about money, so I can write my own.

See for yourself: why cents?

Must know #3 says to store money as cents. Don’t take the book’s word for it; try it. You’ll make a practice folder next to your tracker folder, not inside it. Open a second terminal (or quit your assistant first), and from the tracker folder run:

cd ..
mkdir practice
cd practice

In the practice folder, create floats.go:

package main

import "fmt"

func main() {
    var coffee float64 = 0.1
    tea := 0.2
    fmt.Println(coffee + tea)
}

This file also shows the two ways to create a variable: var with a type, and :=. Run it from inside the practice folder:

go run floats.go
0.30000000000000004

That’s not a Go bug. Computers store float64 numbers in binary, and 0.1 has no exact binary form, just as 1/3 has no exact decimal form. For physics, the tiny error doesn’t matter. For money, it does. Whole cents in an int are always exact.

If you want to go deeper, ask your tutor: “Why can’t a float64 store 0.1 exactly? Explain with an everyday comparison.”

Type the code

Now go back to the tracker folder:

cd ../tracker

Replace main.go with this. Type it; don’t paste:

package main

import "fmt"

func main() {
    fmt.Println(welcome())
    fmt.Println(formatExpense("Coffee", 350))

    amounts := []int{350, 1200, 99}
    fmt.Println("Total:", formatAmount(total(amounts)))
}

func welcome() string {
    return "Welcome to Tracker. Let's see where your money goes."
}

func formatExpense(name string, cents int) string {
    return name + ": " + formatAmount(cents)
}

func formatAmount(cents int) string {
    whole, rest := splitCents(cents)
    return fmt.Sprintf("%d.%02d", whole, rest)
}

func splitCents(cents int) (int, int) {
    return cents / 100, cents % 100
}

func total(amounts []int) int {
    sum := 0
    for _, amount := range amounts {
        sum += amount
    }
    return sum
}

A few things to notice as you type:

If any line puzzles you, ask your tutor about that exact line.

Now run the tests again:

go test ./...
ok      tracker 0.002s

ok means every test passed. (Your time will differ.) Then run the program:

go run .
Welcome to Tracker. Let's see where your money goes.
Coffee: 3.50
Total: 16.49

All three SPEC.md sentences, and Go checked them for you.

Review

Let Go check first

Your Review commands now have a third member:

gofmt -l .
go vet ./...
go test ./...

Silence from the first two and ok from the third mean Go is happy. If go test shows (cached) instead of a time, Go noticed nothing changed since the last passing run and reused the result.

To see each test by name, add -v (for “verbose”):

go test -v ./...
=== RUN   TestWelcome
--- PASS: TestWelcome (0.00s)
=== RUN   TestFormatExpense
--- PASS: TestFormatExpense (0.00s)
=== RUN   TestFormatAmount
--- PASS: TestFormatAmount (0.00s)
=== RUN   TestTotal
--- PASS: TestTotal (0.00s)
PASS
ok      tracker 0.002s

Break it on purpose

A test you’ve never seen fail is a test you can’t fully trust. In main_test.go, change the last row of TestTotal to expect 1650 instead of 1649, and run go test ./...:

--- FAIL: TestTotal (0.00s)
    main_test.go:53: three expenses: total([350 1200 99]) = 1649, want 1650
FAIL
FAIL    tracker 0.002s
FAIL

Read it like a compiler error: which test (TestTotal), which line (53), which case (three expenses), what it got and what it wanted. That message came from your own t.Errorf line. A good failure message tells you what went wrong without opening the code.

Change it back to 1649 and run the tests again.

Now break the code instead of the test. In main.go, change sum := 0 to sum := 1, and run go test ./... again:

--- FAIL: TestTotal (0.00s)
    main_test.go:53: no expenses: total([]) = 1, want 0
    main_test.go:53: one expense: total([350]) = 351, want 350
    main_test.go:53: three expenses: total([350 1200 99]) = 1650, want 1649
FAIL
FAIL    tracker 0.002s
FAIL

Every row of TestTotal fails, because every total is now one cent too high. Notice that the test kept going after the first failure: t.Errorf reports a problem and moves on, so you see every broken row at once. That’s what tests are for: you made a one-character mistake, and Go caught it in under a second. The AI will make mistakes like this too, and your tests will catch those the same way. Change it back and make sure everything passes.

Check it yourself

Be SURE you can explain it. If a line or a table row is still fuzzy, ask your tutor about that exact line before you move on.

Explain

Say it in your own words

Write three or four sentences about how Tracker works now. For example:

If a sentence falls apart halfway, that’s your next question for the AI.

Let the AI quiz you

Ask me two questions about main.go and main_test.go to check that I
understand them. Wait for my answers before you tell me if I'm right.

Running code to find out is still allowed. If the AI asks what formatAmount(7) returns, add a row to the table and let the test tell you.

Write a Learned: line in your commit

git add .
git commit -m "Add tests, format an expense and total amounts" -m "Learned: store money as whole cents in an int, because a float64 can't hold 0.1 exactly."

Your Learned: line should be yours. Pick the thing that surprised you most.

Update AGENTS.md if something surprised you

Did the AI write main.go for you when you only asked for an explanation? Did it suggest float64 for money? Add a rule:

Store money as whole cents in an int, never float64.

Rules like this keep the AI consistent with your project as it grows. Commit the change.

Practice (optional)

Here are five broken programs. Each one fails to compile. Your job: run it, read the error, and fix it. Try to fix each one from the error message alone. If you’re stuck, ask your tutor to explain the message, not to fix the code.

Put them in your practice folder as fix1.go to fix5.go, and run each one with go run fix1.go and so on. Each listing shows what it should print once fixed.

Your editor may underline these files with main redeclared in this block, because several files in one folder each have their own func main. That’s expected: go run with a file name builds only that one file.

fix1.go (should print Coffee: 350)

package main

import "fmt"

func main() {
    name := "Coffee"
    cents := 350
    fmt.Println(name + ": " + cents)
}

fix2.go (should print Amount: 350)

package main

import "fmt"

func main() {
    amount := 350
    count := 3
    fmt.Println("Amount:", amount)
}

fix3.go (should print Whole units: 16)

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 (should print 700; this one shows two errors, and one fix solves both)

package main

import "fmt"

func double(cents int) int {
    result := cents * 2
}

func main() {
    fmt.Println(double(350))
}

fix5.go (should print Total: 1550)

package main

import "fmt"

func main() {
    total := 350
    total := total + 1200
    fmt.Println("Total:", total)
}

If your fix for fix1.go uses string(cents), run go vet fix1.go and reread the box above.

What you’ve done

You turned your spec into tests, watched them fail, wrote the code that made them pass, and broke a test on purpose to learn what failure looks like. Tracker can now format money correctly and add up amounts, and Go checks all of it every time you run go test ./....

In Chapter 3, Tracker gets real lists of expenses and totals them by category. You’ll learn slices, maps and loops properly, and the AI’s role starts to change: by the end of the chapter, you’ll write the code and the AI will review it.

Until then, the habit is set: write down what “done” means, and let Go check it.