Boss lesson · Unit 05
An inventory
Items as structs, stock states as an enum, updates through &mut
What you practise
- Items as structs, stock states as an enum, updates through
&mut, totals and a report
Try a question from this lesson
Pick one
A shop has many items. Each has a name, a count and a price. Which shape of data fits best?
Correct answer
One vector of Item structs
Why
A struct keeps one item's name, count and price together, and a vector holds as many items as the shop has. Three vectors can drift out of step, and text has to be taken apart every time you need a number.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A state is an enum
How well stocked is an item? Out, running low, or fine. That is a short list, and never two at once: an enum.
Low carries how many are left, since that only matters when stock is low. A method works the state out from the count, so the two can never disagree.
enum Stock { Out, Low(i32), Fine }
struct Item { count: i32 }
impl Item {
fn stock(&self) -> Stock {
if self.count == 0 {
Stock::Out
} else if self.count < 5 {
Stock::Low(self.count)
} else {
Stock::Fine
}
}
}Concept
A search can find nothing
To restock "cup" you first have to find it. A search may come back empty, so it returns an Option: Some(index) or None.
usize is the number type Rust uses for indexes and lengths. If the loop ends without a hit, the last line gives None.
struct Item { name: String, count: i32 }
fn find(items: &Vec<Item>, want: &str)
-> Option<usize> {
for i in 0..items.len() {
if items[i].name == want {
return Some(i);
}
}
None
}10 more exercises in the app
- 5× type the answer
- 1× order the lines
- 2× fill the blanks
- 2× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.