Go, lesson 15
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.
Larger programs are easier when you split them into layers that each do one job:
error when a
request cannot be done.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.
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.
A method that might fail returns error, and the message describes the problem from the
user's point of view:
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:
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.
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.
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
reportSample output:
apple: 10 x 2 = 20
pear: 4 x 3 = 12
value: 32
apple: 10 x 2 = 20
pear: 5 x 5 = 25
value: 45Extend 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:
| Problem | Message |
|---|---|
| first word is not a known command | unknown command "<word>" |
| wrong number of words for the command | usage: <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 negative | bad number "<text>" |
| selling or removing an item that does not exist | no item "<name>" |
| selling more than is in stock | only <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
reporterror: 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