Boss lesson · Unit 05
An inventory
A shop's stock as a slice of structs, changed safely through methods.
What you practise
- Items as structs, stock changed through methods, totals and a report, the copy that silently loses an update
Try a question from this lesson
Pick one
A shop keeps its stock in a program. Each item has a name, a price in cents and a stock count, and the whole inventory is a slice of them. What prints?
type Item struct {
Name string
Price int // cents
Stock int
}
inv := []Item{
{"tea", 450, 3},
{"mug", 900, 0},
}
fmt.Println(len(inv), inv[0].Stock)Correct answer
2 3
Why
The slice holds two items, so len(inv) is 2. inv[0] is the tea, and its Stock field is 3. Index first to pick the item, then the dot to pick the field.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The plan
The inventory needs three things.
Data: an Item struct, kept in a slice.
Questions: methods that only read, such as Value(): price times stock.
Changes: methods that update an item, such as Remove(n). They take a pointer receiver, and they return an error when the change is not allowed, so stock can never go below zero.
type Item struct {
Name string
Price int // cents
Stock int
}
func (it Item) Value() int {
return it.Price * it.Stock
}
tea := Item{"tea", 450, 3}
fmt.Println(tea.Value()) // 135011 more exercises in the app
- 4× type the answer
- 2× fill the blanks
- 3× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.