Learn/Go/15. Final project: shop inventory
Lesson 15 of 15
Sign in

Go, lesson 15

Final project: shop inventory

Time to put the whole course to work. You will build a small inventory system for a shop. It reads commands, one per line, keeps track of stock and sales, reports problems as errors, and prints a sorted report. Nothing here is new; the challenge is fitting the pieces together cleanly.

Plan before you code

Larger programs are easier when you split them into layers that each do one job:

  1. Data: a struct for one item and a struct for the whole inventory.
  2. Operations: methods on the inventory that change it and return an error when a request cannot be done.
  3. Parsing: turn one line of text into a call to an operation.
  4. Main loop: read lines, dispatch them, print errors, keep going.

Each layer only talks to the one next to it. The methods never print, and the parser never touches the map directly. That makes each part small enough to reason about.

The data

Storing *Item in the map lets methods change an item's quantity in place (lesson 13 explains why). Money is kept as whole numbers on purpose: floats cannot represent most decimal amounts exactly, and shops do not like rounding surprises.

2 exercises to try what you just read.

Exercise 1

Stocking the shelves

Press Ctrl Enter or Check to test your code.

Exercise 2

Open for business

Press Ctrl Enter or Check to test your code.

Operations return errors

A method that might fail returns error, and the message describes the problem from the user's point of view:

Dispatching commands

strings.Fields splits a line into words. A switch on the first word picks the operation, and a small helper converts number arguments with strconv.Atoi, turning failures into errors. Because each branch either returns an error or nil, the main loop handles every failure in one place:

A sorted report

Map order is random, so the report collects names with slices.Sorted(maps.Keys(inv.items)) and walks them in order. Summing Qty * Price along the way gives the stock value.

Building it in two steps

The first exercise handles only add and report. The second exercise starts from a working version of the first and adds selling, removing and error handling. Run your code often with small inputs, and add one command at a time.

Further reading

  • Effective Go
  • Package strings
  • Package strconv
  • Go blog: Error handling and Go

Each input line is a command. Support two commands:

  • add <name> <qty> <price> adds qty units of an item. If the item already exists, increase its quantity and replace its price with the new one.
  • report prints every item sorted by name as <name>: <qty> x <price> = <qty*price>, then a line value: <sum of all item values>. If there are no items, print (empty) before the value line.

All numbers are whole numbers. You can assume every line in this exercise is valid.

Sample input:

add pear 4 3
add apple 10 2
report
add pear 1 5
report

Sample output:

apple: 10 x 2 = 20
pear: 4 x 3 = 12
value: 32
apple: 10 x 2 = 20
pear: 5 x 5 = 25
value: 45

Extend the inventory into a full shop. Commands:

  • add <name> <qty> <price>: as before.
  • sell <name> <qty>: reduce the item's quantity and add qty * price to the shop's sales.
  • remove <name>: delete the item completely.
  • report: as before, plus a final line sales: <total sales so far>.

When a command cannot be done, print error: <message> and change nothing. Messages:

ProblemMessage
first word is not a known commandunknown command "<word>"
wrong number of words for the commandusage: <command> ... exactly as usage: add NAME QTY PRICE, usage: sell NAME QTY, usage: remove NAME, usage: report
a number argument is not a whole number, or is negativebad number "<text>"
selling or removing an item that does not existno item "<name>"
selling more than is in stockonly <qty> <name> left

Blank lines are ignored.

Sample input:

Sample output:

type Item struct {
	Name  string
	Qty   int
	Price int // whole coins, to avoid floating-point rounding
}

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

func NewInventory() *Inventory {
	return &Inventory{items: map[string]*Item{}}
}
func (inv *Inventory) Remove(name string) error {
	if _, ok := inv.items[name]; !ok {
		return fmt.Errorf("no item %q", name)
	}
	delete(inv.items, name)
	return nil
}
if err := run(inv, line); err != nil {
	fmt.Println("error:", err)
}
add tea 5 4
sell tea 2
sell tea 9
sell cake 1
remove tea x
buy tea
report
error: only 3 tea left
error: no item "cake"
error: usage: remove NAME
error: unknown command "buy"
tea: 3 x 4 = 12
value: 12
sales: 8