A shop keeps track of how many pieces of each item it has: the item's stock. The stock can never go below 0, and it changes only when pieces are sold or new ones arrive. So the stock is a private field, changed only through two methods that check the rules. The item's name has no rules to protect, so any code can read it.
As in the Access Modifiers lesson, Go decides by the first letter of a name: a field that starts with an uppercase letter is exported, visible to code outside the package, and a lowercase one is unexported, hidden from it. Write:
- The
InventoryItemstruct, with an exported fieldName(astring) and an unexported fieldstock(anint). NewInventoryItem(name, stock): returns an item with that name and that many pieces in stock.sell(n)sellsnpieces. Ifnis at least 1 and at most the stock, it lowers the stock bynand returnstrue. Otherwise it changes nothing and returnsfalse: selling 0 pieces, a negative number of pieces, or more pieces than there are in stock is refused.restock(n)addsnpieces to the stock whennis at least 1, and ignoresnotherwise.getStock()returns the stock. It is the only way for other code to read it.
sell and restock change the item, so they have a pointer receiver, (this *InventoryItem); getStock only reads, so a value receiver is enough. The starter code already has these headers.
Each test case creates one item with NewInventoryItem, then applies a list of operations to it, in order. The output has one line per test case: the item's Name and a colon, then what each sell and getStock call returns, separated by spaces, with sell's answer printed as True or False.
Example 1:
Input:
NewInventoryItem("Pencil", 5)
sell(3)
getStock()
sell(5)
getStock()
restock(10)
getStock()
Output: Pencil: True 2 False 2 12
Explanation: Selling 3 of the 5 pencils works and leaves 2. Selling 5 more is refused, because only 2 are left,
and the stock stays 2. restock(10) brings it to 12.
Example 2:
Input:
NewInventoryItem("Mug", 4)
sell(4)
getStock()
sell(1)
getStock()
Output: Mug: True 0 False 0
Explanation: Selling all 4 mugs is allowed and leaves 0. With nothing left, even one mug can't be sold.
Example 3:
Input:
NewInventoryItem("Lamp", 2)
sell(0)
sell(-3)
restock(0)
restock(-5)
getStock()
restock(1)
sell(3)
getStock()
Output: Lamp: False False 2 True 0
Explanation: Selling 0 or -3 lamps is refused, and restocking 0 or -5 lamps is ignored, so the stock is still 2.
After restock(1) there are 3 lamps, and selling all 3 works.
Constraints:
- A name is one word of English letters.
0 <= stock <= 104when the item is created. -104 <= n <= 104in everysellandrestock.- A test case has from 1 to 1000 operations, and at least one of them is a
sellor agetStock.
Free plan: 30 tutor messages. PRO is unlimited.
