By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Part 1 had one large weakness: every run started with an empty slice, so an expense added with add disappeared the moment the program exited. A real tracker must remember. This project fixes that by loading expenses from a JSON file when Penny starts and saving them back after every change.
The file is called penny.json and lives next to the program. Two new functions own all the file work: loadExpenses reads the file, and saveExpenses writes it. main does not touch encoding/json at all; it asks for the slice and saves it when something changed.
| Function | Rule | Why |
|---|---|---|
loadExpenses(path) | A missing file returns an empty list and nil error | A brand-new Penny has nothing to load; that is not a failure |
loadExpenses(path) | A broken file returns a wrapped error | The user needs to know the file is damaged, not silently lose data |
saveExpenses(path, expenses) | Marshal with indentation and write mode 0644 | Readable file, standard permissions |
saveExpenses(path, expenses) | Wrap every failure with %w | errors.Is still works for the caller |
The missing-file rule is the interesting one. When os.ReadFile fails with fs.ErrNotExist, loadExpenses returns []Expense{}, nil. Every other failure is returned as a wrapped error. That single special case is what lets go run . work the first time, before penny.json exists.
main.go and storage.goSplit the program across two files in the same folder and the same package. The helper functions and main stay in main.go; all the JSON and file code moves to storage.go. The two files already share the Expense type and the expensesPath constant because they are one package. Type both files exactly as shown.
// ==== file: main.go ====
package main
import (
"fmt"
"math"
"os"
"strconv"
"strings"
)
// Expense is one thing Penny remembers.
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
// formatCents turns integer cents into dollars and cents: 1250 -> $12.50.
func formatCents(cents int) string {
if cents < 0 {
return "-" + formatCents(-cents)
}
return fmt.Sprintf("$%d.%02d", cents/100, cents%100)
}
// dollarsToCents parses "12.50" into 1250 and rejects zero or negative input.
func dollarsToCents(input string) (int, error) {
value, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, fmt.Errorf("amount %q is not a number", input)
}
cents := int(math.Round(value * 100))
if cents <= 0 {
return 0, fmt.Errorf("amount %q must be greater than zero", input)
}
return cents, nil
}
// nextID returns one more than the highest ID in the slice.
func nextID(expenses []Expense) int {
highest := 0
for _, expense := range expenses {
if expense.ID > highest {
highest = expense.ID
}
}
return highest + 1
}
// helpText is printed when Penny is run with no command.
func helpText() string {
return `Penny - a tiny expense tracker
Usage:
penny add <dollars> <description...>
penny list
penny sum
penny remove <id>
penny help
Examples:
penny add 12.50 Coffee with Sam
penny remove 1
Expenses are saved to penny.json after every change.`
}
func main() {
expenses, err := loadExpenses(expensesPath)
if err != nil {
fmt.Println("error:", err)
return
}
args := os.Args[1:]
if len(args) == 0 || args[0] == "help" {
fmt.Println(helpText())
return
}
changed := false
switch args[0] {
case "add":
if len(args) < 3 {
fmt.Println("usage: penny add <dollars> <description...>")
return
}
cents, err := dollarsToCents(args[1])
if err != nil {
fmt.Println("error:", err)
return
}
expense := Expense{
ID: nextID(expenses),
Description: strings.Join(args[2:], " "),
Cents: cents,
Category: "uncategorised",
}
expenses = append(expenses, expense)
changed = true
fmt.Printf("added #%d: %s (%s)\n", expense.ID, expense.Description, formatCents(expense.Cents))
case "list":
if len(expenses) == 0 {
fmt.Println("no expenses yet")
return
}
for _, expense := range expenses {
fmt.Printf("#%d %-20s %8s\n", expense.ID, expense.Description, formatCents(expense.Cents))
}
case "sum":
total := 0
for _, expense := range expenses {
total += expense.Cents
}
fmt.Printf("total: %s across %d expense(s)\n", formatCents(total), len(expenses))
case "remove":
if len(args) < 2 {
fmt.Println("usage: penny remove <id>")
return
}
id, err := strconv.Atoi(args[1])
if err != nil {
fmt.Printf("error: %q is not an ID\n", args[1])
return
}
removed := false
for index, expense := range expenses {
if expense.ID == id {
expenses = append(expenses[:index], expenses[index+1:]...)
removed = true
changed = true
fmt.Printf("removed #%d: %s\n", expense.ID, expense.Description)
break
}
}
if !removed {
fmt.Printf("no expense with id %d\n", id)
}
default:
fmt.Printf("unknown command %q\n\n%s\n", args[0], helpText())
}
if changed {
if err := saveExpenses(expensesPath, expenses); err != nil {
fmt.Println("error:", err)
}
}
}
// ==== file: storage.go ====
package main
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
)
// expensesPath is where Penny keeps its data.
const expensesPath = "penny.json"
// loadExpenses reads the JSON file at path.
// A missing file is not a failure: a new Penny starts with an empty list.
func loadExpenses(path string) ([]Expense, error) {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return []Expense{}, nil
}
if err != nil {
return nil, fmt.Errorf("loadExpenses: read %s: %w", path, err)
}
var expenses []Expense
if err := json.Unmarshal(data, &expenses); err != nil {
return nil, fmt.Errorf("loadExpenses: parse %s: %w", path, err)
}
return expenses, nil
}
// saveExpenses writes all expenses to path as indented JSON.
func saveExpenses(path string, expenses []Expense) error {
data, err := json.MarshalIndent(expenses, "", " ")
if err != nil {
return fmt.Errorf("saveExpenses: encode: %w", err)
}
data = append(data, '\n')
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("saveExpenses: write %s: %w", path, err)
}
return nil
}Run these commands in order inside the project folder. This time each run loads the file left by the previous one, so the slice is no longer empty.
go run . add 12.50 Coffee
# added #1: Coffee ($12.50)
go run . add 3.25 Bus fare
# added #2: Bus fare ($3.25)
go run . list
# #1 Coffee $12.50
# #2 Bus fare $3.25
go run . sum
# total: $15.75 across 2 expense(s)
go run . remove 1
# removed #1: Coffee
go run . list
# #2 Bus fare $3.25After the two add commands, open penny.json in your editor. It is the indented JSON you met in the last lesson, with the Penny fields named by their struct tags.
cat penny.jsonTwo cases need care. First, a missing file: delete penny.json and run go run . list. Penny prints no expenses yet and exits normally, because loadExpenses treats a missing file as an empty list. The file is only created when something is saved.
Second, a corrupt file: open penny.json, delete everything, and type {broken. Now run go run . list. Penny refuses to guess, prints the wrapped parse error, and exits without changing the file. That is the correct behaviour: a damaged data file must never be silently replaced with an empty list.
# macOS/Linux: replace the whole file with broken text.
# On Windows, open penny.json in your editor and type {broken
echo '{broken' > penny.json
go run . list
# error: loadExpenses: parse penny.json: invalid character 'b' looking for beginning of object key stringThe same wrapping appears for permission problems and unreadable paths. main prints the error and stops before running any command, so there is no risk of saving over a file the program could not read.
| Situation | loadExpenses returns | What the user sees |
|---|---|---|
penny.json does not exist | an empty slice and nil | Commands work as if Penny is new |
| Valid JSON array | the decoded slice and nil | The saved expenses |
| Broken JSON | nil and a wrapped parse error | error: loadExpenses: parse penny.json: ... |
| Unreadable file | nil and a wrapped read error | error: loadExpenses: read penny.json: ... |
Saving is the mirror image: json.MarshalIndent produces the bytes, a trailing newline is appended so the file ends cleanly, and os.WriteFile writes with 0644. Every mutation sets changed = true, and the last block in main saves exactly once. Read-only commands such as list and sum return before that block, so they never rewrite the file.
go run . with no arguments prints help and does not crash, with or without a penny.json file.list shows both of them.sum prints total: $15.75 across 2 expense(s) after two known additions.remove deletes the item from the file, not only from the screen.list, and see no expenses yet instead of an error.list, and see an error that names the file.penny.json is valid JSON with lowercase keys and integer cents.gofmt -w . makes no changes and go vet ./... is silent.main saves first, an unreadable file is replaced before the user ever sees the error.no such file, and Penny appears broken before it has been used.changed in every case that mutates the slice.12.5 values cannot be summed exactly. Keep cents as integers in the file.os.WriteFile for whole-file saves.Add a clear command that empties the list and saves. Then break the program on purpose: catch the error from saveExpenses and print it instead of ignoring it. Finally, make a copy of a valid penny.json, corrupt the original, and confirm that reversing the copy restores every expense.
Key takeaways
loadExpenses and saveExpenses keep all file and JSON code in one place.
A missing penny.json returns an empty list and no error; a corrupt one returns a wrapped error.
Save after every mutation, and only when changed is true.
json.MarshalIndent plus os.WriteFile writes readable JSON; integer cents keep money exact.
Wrapping errors with %w gives the user a message that names the file and keeps errors.Is usable.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.