TExcelTAD
Home › Go › Go Mini Project

Go Mini Project: Inventory CLI

Let's put everything together and build a small but realistic program: a command-line inventory manager for a little shop. It reads commands like add apple 12 0.45, keeps stock in memory, reports problems as errors, prints a sorted report and exports JSON.

We'll build it in five steps. Each step is a complete program you can run and modify.

Step Feature Go topics
1 Data model structs, maps, methods
2 Add and remove stock with validation pointer receivers, errors, sentinel errors
3 A command interpreter strings, strconv, switch
4 Sorted report and totals slices, Printf widths
5 JSON export and the finished tool encoding/json, struct tags

Real CLIs read commands from the terminal (bufio.Scanner on os.Stdin). Playgrounds have no keyboard input, so our program reads its commands from a multi-line string instead — swapping in os.Stdin later is a two-line change.

Step 1: The data model

An Item holds a name, quantity and unit price. The Inventory stores items in a map keyed by name for fast lookup.

go · try it yourself
package main

import "fmt"

type Item struct {
	Name  string
	Qty   int
	Price float64
}

func (it Item) Value() float64 {
	return float64(it.Qty) * it.Price
}

type Inventory struct {
	items map[string]*Item
}

func NewInventory() *Inventory {
	return &Inventory{items: make(map[string]*Item)}
}

func main() {
	inv := NewInventory()
	inv.items["apple"] = &Item{Name: "apple", Qty: 12, Price: 0.45}
	inv.items["bread"] = &Item{Name: "bread", Qty: 3, Price: 2.10}

	fmt.Println(len(inv.items), "items")
	fmt.Printf("apple stock value: %.2f\n", inv.items["apple"].Value())
}
2 items
apple stock value: 5.40

Storing *Item pointers in the map lets us update an item in place (inv.items["apple"].Qty += 5); with plain Item values we'd have to copy, modify and store it back.

Step 2: Add and remove, with errors

Changing stock goes through methods that validate their input. Callers can detect specific problems with errors.Is because we define sentinel errors.

go · try it yourself
package main

import (
	"errors"
	"fmt"
)

var (
	ErrNotFound     = errors.New("item not found")
	ErrInvalidQty   = errors.New("quantity must be positive")
	ErrInsufficient = errors.New("not enough stock")
)

type Item struct {
	Name  string
	Qty   int
	Price float64
}

type Inventory struct {
	items map[string]*Item
}

func NewInventory() *Inventory {
	return &Inventory{items: make(map[string]*Item)}
}

func (inv *Inventory) Add(name string, qty int, price float64) error {
	if qty <= 0 {
		return ErrInvalidQty
	}
	if it, ok := inv.items[name]; ok {
		it.Qty += qty
		it.Price = price // latest price wins
		return nil
	}
	inv.items[name] = &Item{Name: name, Qty: qty, Price: price}
	return nil
}

func (inv *Inventory) Remove(name string, qty int) error {
	it, ok := inv.items[name]
	if !ok {
		return fmt.Errorf("remove %q: %w", name, ErrNotFound)
	}
	if qty <= 0 {
		return ErrInvalidQty
	}
	if qty > it.Qty {
		return fmt.Errorf("remove %d %s (have %d): %w", qty, name, it.Qty, ErrInsufficient)
	}
	it.Qty -= qty
	if it.Qty == 0 {
		delete(inv.items, name)
	}
	return nil
}

func main() {
	inv := NewInventory()
	fmt.Println(inv.Add("apple", 12, 0.45))
	fmt.Println(inv.Add("apple", 0, 0.45))
	fmt.Println(inv.Remove("apple", 20))
	fmt.Println(inv.Remove("mango", 1))

	err := inv.Remove("apple", 12)
	fmt.Println(err, len(inv.items))

	err = inv.Remove("apple", 1)
	fmt.Println(errors.Is(err, ErrNotFound))
}
<nil>
quantity must be positive
remove 20 apple (have 12): not enough stock
remove "mango": item not found
<nil> 0
true

Step 3: A command interpreter

Now we parse text commands. strings.Fields splits a line into words; a switch on the first word picks the action; strconv converts the numbers. Every failure becomes an error that we print with its line number — the program keeps going.

go · try it yourself
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

type Item struct {
	Name  string
	Qty   int
	Price float64
}

type Inventory struct{ items map[string]*Item }

func (inv *Inventory) Add(name string, qty int, price float64) error {
	if qty <= 0 {
		return errors.New("quantity must be positive")
	}
	if it, ok := inv.items[name]; ok {
		it.Qty += qty
		it.Price = price
		return nil
	}
	inv.items[name] = &Item{name, qty, price}
	return nil
}

func (inv *Inventory) Execute(line string) (string, error) {
	f := strings.Fields(line)
	if len(f) == 0 {
		return "", nil // ignore blank lines
	}
	switch cmd := f[0]; cmd {
	case "add":
		if len(f) != 4 {
			return "", errors.New("usage: add <name> <qty> <price>")
		}
		qty, err := strconv.Atoi(f[2])
		if err != nil {
			return "", fmt.Errorf("bad quantity %q", f[2])
		}
		price, err := strconv.ParseFloat(f[3], 64)
		if err != nil {
			return "", fmt.Errorf("bad price %q", f[3])
		}
		if err := inv.Add(f[1], qty, price); err != nil {
			return "", err
		}
		return fmt.Sprintf("added %d %s", qty, f[1]), nil
	default:
		return "", fmt.Errorf("unknown command %q", cmd)
	}
}

func main() {
	script := `add apple 12 0.45
add bread two 2.10
add milk 6

add bread 3 2.10
sell apple 2`

	inv := &Inventory{items: map[string]*Item{}}
	for i, line := range strings.Split(script, "\n") {
		msg, err := inv.Execute(line)
		switch {
		case err != nil:
			fmt.Printf("line %d: error: %v\n", i+1, err)
		case msg != "":
			fmt.Printf("line %d: %s\n", i+1, msg)
		}
	}
}
line 1: added 12 apple
line 2: error: bad quantity "two"
line 3: error: usage: add <name> <qty> <price>
line 5: added 3 bread
line 6: error: unknown command "sell"

Step 4: A sorted report

Maps have no order, so the report collects the items into a slice and sorts it — by name here, but you could sort by value just as easily with slices.SortFunc. Printf widths line the columns up.

go · try it yourself
package main

import (
	"cmp"
	"fmt"
	"maps"
	"slices"
	"strings"
)

type Item struct {
	Name  string
	Qty   int
	Price float64
}

func (it Item) Value() float64 { return float64(it.Qty) * it.Price }

func report(items map[string]*Item) string {
	list := slices.Collect(maps.Values(items))
	slices.SortFunc(list, func(a, b *Item) int { return cmp.Compare(a.Name, b.Name) })

	var sb strings.Builder
	fmt.Fprintf(&sb, "%-8s %5s %8s %9s\n", "ITEM", "QTY", "PRICE", "VALUE")
	total, units := 0.0, 0
	for _, it := range list {
		fmt.Fprintf(&sb, "%-8s %5d %8.2f %9.2f\n", it.Name, it.Qty, it.Price, it.Value())
		total += it.Value()
		units += it.Qty
	}
	fmt.Fprintf(&sb, "%-8s %5d %8s %9.2f\n", "TOTAL", units, "", total)
	return sb.String()
}

func main() {
	items := map[string]*Item{
		"rice":   {"rice", 8, 1.95},
		"apple":  {"apple", 12, 0.45},
		"coffee": {"coffee", 2, 7.80},
		"bread":  {"bread", 3, 2.10},
	}
	fmt.Print(report(items))
}
ITEM       QTY    PRICE     VALUE
apple       12     0.45      5.40
bread        3     2.10      6.30
coffee       2     7.80     15.60
rice         8     1.95     15.60
TOTAL       25              42.90

slices.Collect(maps.Values(items)) turns the map's values into a slice in one line; the explicit sort then fixes the order.

Step 5: The finished tool

The final version combines everything and adds two commands: report and export, which prints the inventory as JSON using struct tags. The command script now exercises every feature.

go · try it yourself
package main

import (
	"cmp"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"slices"
	"strconv"
	"strings"
)

var (
	ErrNotFound     = errors.New("item not found")
	ErrInvalidQty   = errors.New("quantity must be positive")
	ErrInsufficient = errors.New("not enough stock")
)

type Item struct {
	Name  string  `json:"name"`
	Qty   int     `json:"qty"`
	Price float64 `json:"price"`
}

func (it Item) Value() float64 { return float64(it.Qty) * it.Price }

type Inventory struct{ items map[string]*Item }

func NewInventory() *Inventory { return &Inventory{items: map[string]*Item{}} }

func (inv *Inventory) Add(name string, qty int, price float64) error {
	if qty <= 0 {
		return ErrInvalidQty
	}
	if it, ok := inv.items[name]; ok {
		it.Qty += qty
		it.Price = price
		return nil
	}
	inv.items[name] = &Item{name, qty, price}
	return nil
}

func (inv *Inventory) Remove(name string, qty int) error {
	it, ok := inv.items[name]
	switch {
	case !ok:
		return fmt.Errorf("%q: %w", name, ErrNotFound)
	case qty <= 0:
		return ErrInvalidQty
	case qty > it.Qty:
		return fmt.Errorf("%s has %d: %w", name, it.Qty, ErrInsufficient)
	}
	it.Qty -= qty
	if it.Qty == 0 {
		delete(inv.items, name)
	}
	return nil
}

func (inv *Inventory) Sorted() []*Item {
	list := slices.Collect(maps.Values(inv.items))
	slices.SortFunc(list, func(a, b *Item) int { return cmp.Compare(a.Name, b.Name) })
	return list
}

func (inv *Inventory) Report() string {
	var sb strings.Builder
	total := 0.0
	for _, it := range inv.Sorted() {
		fmt.Fprintf(&sb, "  %-7s %4d x %5.2f = %6.2f\n", it.Name, it.Qty, it.Price, it.Value())
		total += it.Value()
	}
	fmt.Fprintf(&sb, "  total value: %.2f", total)
	return sb.String()
}

func (inv *Inventory) Execute(line string) (string, error) {
	f := strings.Fields(line)
	if len(f) == 0 || strings.HasPrefix(f[0], "#") {
		return "", nil
	}
	switch f[0] {
	case "add":
		if len(f) != 4 {
			return "", errors.New("usage: add <name> <qty> <price>")
		}
		qty, err := strconv.Atoi(f[2])
		if err != nil {
			return "", fmt.Errorf("bad quantity %q", f[2])
		}
		price, err := strconv.ParseFloat(f[3], 64)
		if err != nil {
			return "", fmt.Errorf("bad price %q", f[3])
		}
		if err := inv.Add(f[1], qty, price); err != nil {
			return "", err
		}
		return fmt.Sprintf("added %d %s", qty, f[1]), nil
	case "sell":
		if len(f) != 3 {
			return "", errors.New("usage: sell <name> <qty>")
		}
		qty, err := strconv.Atoi(f[2])
		if err != nil {
			return "", fmt.Errorf("bad quantity %q", f[2])
		}
		if err := inv.Remove(f[1], qty); err != nil {
			return "", err
		}
		return fmt.Sprintf("sold %d %s", qty, f[1]), nil
	case "report":
		return "report:\n" + inv.Report(), nil
	case "export":
		data, err := json.MarshalIndent(inv.Sorted(), "", "  ")
		if err != nil {
			return "", err
		}
		return string(data), nil
	default:
		return "", fmt.Errorf("unknown command %q", f[0])
	}
}

func main() {
	script := `# morning delivery
add apple 12 0.45
add coffee 4 7.80
add bread 5 2.10
sell bread 2
sell coffee 9
sell mango 1
add bread 2 2.25
sell apple 12
report
export`

	inv := NewInventory()
	errCount := 0
	for i, line := range strings.Split(script, "\n") {
		out, err := inv.Execute(line)
		if err != nil {
			errCount++
			fmt.Printf("line %2d: error: %v\n", i+1, err)
			continue
		}
		if out != "" {
			fmt.Println(out)
		}
	}
	fmt.Println("finished with", errCount, "errors")
}
added 12 apple
added 4 coffee
added 5 bread
sold 2 bread
line  6: error: coffee has 4: not enough stock
line  7: error: "mango": item not found
added 2 bread
sold 12 apple
report:
  bread      5 x  2.25 =  11.25
  coffee     4 x  7.80 =  31.20
  total value: 42.45
[
  {
    "name": "bread",
    "qty": 5,
    "price": 2.25
  },
  {
    "name": "coffee",
    "qty": 4,
    "price": 7.8
  }
]
finished with 2 errors

Reading real input

To turn this into a real terminal tool, replace the script loop with a scanner over standard input:

go
scanner := bufio.NewScanner(os.Stdin)
for lineNo := 1; scanner.Scan(); lineNo++ {
	out, err := inv.Execute(scanner.Text())
	// ... same handling as before
}

Then go build and run ./inventory < commands.txt, or type commands interactively.

Ideas for extending it

  • Persist the inventory: write the JSON to a file with os.WriteFile and load it on start with json.Unmarshal.
  • Add a low <n> command that lists items with fewer than n units.
  • Move Inventory into its own package inventory and write table-driven tests for Add and Remove.
  • Store prices as integer cents to avoid floating-point rounding.
  • Protect the map with a sync.Mutex and accept commands from several goroutines.

Test yourself

Why does the inventory map store *Item instead of Item?

  1. Pointers use less memory for small structs
  2. So an item can be updated in place through the map
  3. Maps cannot store structs
  4. JSON requires pointers

Why does Sorted() sort the items before reporting?

  1. Sorting is required by json
  2. Map iteration order is random, so output would change between runs
  3. To remove duplicates
  4. To make lookups faster

How does a caller check whether a wrapped error is ErrNotFound?

  1. err == ErrNotFound
  2. errors.Is(err, ErrNotFound)
  3. err.Error() == "item not found"
  4. errors.As(err, ErrNotFound)