Skip to content
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) puts qty units of the item name into the warehouse;
  • func (inv *Inventory) Take(name string, qty int) error takes them out and returns nil;
  • func (inv *Inventory) Count(name string) int returns how many units of the item the warehouse holds;
  • func (inv *Inventory) Names() []string returns 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) and Add("apple", 3): Count("apple") → 8
  • when Count("pear") is 2: Take("pear", 3) → ErrNotEnough, and Count("pear") stays 2
  • after Add("pear", 2) and Add("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.

inventory.go — go
go · 30 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way