Exercise · Final project · lesson 7 of 7
Exercise: inventory
Write the type Inventory, a warehouse that counts the units of each item. Keep the quantities in a map[string]int; add the field yourself. The function func NewInventory() *Inventory creates an empty warehouse, and the methods are these:
func (inv *Inventory) Add(name string, qty int)putsqtyunits of the itemnameinto the warehouse;func (inv *Inventory) Take(name string, qty int) errortakes them out and returnsnil;func (inv *Inventory) Count(name string) intreturns how many units of the item the warehouse holds;func (inv *Inventory) Names() []stringreturns the item names in alphabetical order.
The stub declares two errors. If the warehouse has no item name, Take returns ErrUnknownItem, and if there are fewer units than qty, it returns ErrNotEnough; in both cases the warehouse does not change.
- after
Add("apple", 5)andAdd("apple", 3):Count("apple")→8 - when
Count("pear")is2:Take("pear", 3)→ErrNotEnough, andCount("pear")stays2 - after
Add("pear", 2)andAdd("apple", 5):Names()→[apple pear]
Constraints: qty is positive; Count returns 0 for an unknown item; an item taken out in full leaves the warehouse, and Names no longer returns it.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.