By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
This is the first real version of Penny: a command-line expense tracker you can run with go run .. It reads one command from the command line, acts on an in-memory slice of Expense values, prints the result, and exits. The four commands are add, list, sum and remove, plus help.
| Command | What it does | Example |
|---|---|---|
add <dollars> <description...> | Creates an expense with the next ID | go run . add 12.50 Coffee |
list | Prints every expense in the slice | go run . list |
sum | Adds up all cents and prints the total | go run . sum |
remove <id> | Deletes one expense by ID | go run . remove 1 |
help | Prints the usage text | go run . help |
Make a new folder for this project. You can reuse your course folder or start a second one; what matters is that it has its own go.mod.
# 1. Create the folder and enter it.
mkdir penny
cd penny
# 2. Make it a Go module.
go mod init penny
# 3. Create main.go in your editor and type the program below.main.goType this program in full. It is longer than anything so far, so read it in pieces: the type and formatting helpers at the top, the argument parsing and switch in main, and one case per command. The comments mark each piece.
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 kept in memory for now, so every run starts empty.`
}
func main() {
expenses := []Expense{}
args := os.Args[1:]
if len(args) == 0 || args[0] == "help" {
fmt.Println(helpText())
return
}
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)
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
}
for index, expense := range expenses {
if expense.ID != id {
continue
}
expenses = append(expenses[:index], expenses[index+1:]...)
fmt.Printf("removed #%d: %s\n", expense.ID, expense.Description)
return
}
fmt.Printf("no expense with id %d\n", id)
default:
fmt.Printf("unknown command %q\n\n%s\n", args[0], helpText())
}
}From the penny folder, run the program with no arguments to see the help text, then try each command. The commands below are each a separate run, and the comment after each one shows what it prints. Comments are ignored by the shell, so you can paste the block into a terminal.
go run .
go run . add 12.50 Coffee
# added #1: Coffee ($12.50)
go run . list
# no expenses yet
go run . sum
# total: $0.00 across 0 expense(s)
go run . remove 1
# no expense with id 1
go run . add 0 Coffee
# error: amount "0" must be greater than zero
go run . spend 5
# unknown command "spend"
# (followed by the same help text)os.Args[1:] drops the program name and gives you the words the user typed. With no words, the program prints helpText() and returns. Otherwise a switch on args[0] chooses the command. Each case validates its own arguments before acting, which is why running penny add with no amount prints a usage line instead of crashing.
| Function | Job | Why it lives on its own |
|---|---|---|
formatCents | Prints integer cents as $12.50 | Every command needs it, and money must never use floats |
dollarsToCents | Parses "12.50" into 1250 | One place for the rules: numbers only, greater than zero |
nextID | Returns highest ID plus one | IDs stay unique even after a remove |
helpText | Returns the usage text | Help can be printed from several places without repeating it |
Money is stored as integer cents, not as a float64. A float cannot represent 0.10 exactly, and repeated additions produce amounts such as $0.30000000000000004. dollarsToCents converts at the edge of the program with math.Round, and everything inside works on ints.
go run . with no arguments prints the full help text and exits.go run . help prints the same text.go run . add 12.50 Coffee prints added #1: Coffee ($12.50).go run . add 0 Coffee prints an error and does not add anything.go run . add abc Coffee prints a different, clear error.go run . list on an empty slice prints no expenses yet.go run . sum prints total: $0.00 across 0 expense(s).go run . remove 99 prints no expense with id 99.go run . spend 5 prints an unknown-command line followed by help.gofmt -w main.go makes no changes and go vet ./... is silent.These are the mistakes almost everyone makes on the first run of this project. Read them before you debug, so you can recognise the symptom.
args[2] only gives the first word of the description, so Coffee with Sam becomes Coffee.12.5 in a Cents field and printing it produces $0.12. Convert to cents once, at the boundary.fmt.Sprintf("$%d.%d", cents/100, cents%100) prints $12.5 for 1250. %02d is what makes it $12.50.penny alone.Add a count command that prints the number of expenses, and then make add assign the category food when the description contains coffee or tea. Keep the help text in sync with the new command, and add a line to your definition of done for it. In part 2, these commands will work on data that survives a restart.
Key takeaways
A CLI reads os.Args[1:], switches on the first word, and validates the rest.
One command per process means an in-memory slice starts empty every run.
Money lives in integer cents; parse dollars once with ParseFloat and math.Round.
formatCents prints $12.50, and %02d is what keeps the cents readable.
IDs are highest-plus-one so they stay unique after removals.
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.