Rust Mini Project: Shop Inventory
In this project you will build a small inventory manager for a corner shop, one step at a time. Each step adds a feature and reuses what you learned in the course: structs, impl blocks, vectors, Option/Result, enums with match, and iterators. Every step is a complete program you can run and modify.
| Step | Feature | Concepts |
|---|---|---|
| 1 | Describe an item | structs, methods, formatting |
| 2 | Store items in an inventory | Vec, &mut self, Option |
| 3 | Sell and restock safely | Result, custom error enum |
| 4 | Reports | iterators, closures, sorting |
| 5 | Process a list of commands | enums, match, putting it together |
Step 1: An item
Start with a struct for one product. Prices are stored in cents as an integer, which avoids floating-point rounding surprises with money.
struct Item {
name: String,
price_cents: u32,
quantity: u32,
}
impl Item {
fn new(name: &str, price_cents: u32, quantity: u32) -> Item {
Item { name: name.to_string(), price_cents, quantity }
}
fn stock_value(&self) -> u32 {
self.price_cents * self.quantity
}
}
fn money(cents: u32) -> String {
format!("${}.{:02}", cents / 100, cents % 100)
}
fn main() {
let apple = Item::new("apple", 45, 30);
println!("{} costs {} and we have {}", apple.name, money(apple.price_cents), apple.quantity);
println!("stock value: {}", money(apple.stock_value()));
}apple costs $0.45 and we have 30
stock value: $13.50
{:02} pads the cents with a leading zero, so 5 cents prints as 05.
Step 2: The inventory
Next, an Inventory struct owns a Vec<Item>. Adding an item that already exists should increase its quantity instead of creating a duplicate, so we need a way to find an item: find_mut returns Option<&mut Item>.
struct Item {
name: String,
price_cents: u32,
quantity: u32,
}
struct Inventory {
items: Vec<Item>,
}
impl Inventory {
fn new() -> Inventory {
Inventory { items: Vec::new() }
}
fn find_mut(&mut self, name: &str) -> Option<&mut Item> {
self.items.iter_mut().find(|item| item.name == name)
}
fn add(&mut self, name: &str, price_cents: u32, quantity: u32) {
match self.find_mut(name) {
Some(item) => item.quantity += quantity,
None => self.items.push(Item {
name: name.to_string(),
price_cents,
quantity,
}),
}
}
fn print(&self) {
for item in &self.items {
println!("{:<8} {:>4} pcs @ {:>3} cents", item.name, item.quantity, item.price_cents);
}
}
}
fn main() {
let mut inv = Inventory::new();
inv.add("apple", 45, 30);
inv.add("bread", 250, 8);
inv.add("milk", 120, 12);
inv.add("apple", 45, 20); // existing item: quantity goes up
inv.print();
}apple 50 pcs @ 45 cents
bread 8 pcs @ 250 cents
milk 12 pcs @ 120 cents
The format specs {:<8} (left-align in 8 columns) and {:>4} (right-align in 4) give us a neat table.
Step 3: Selling with error handling
Selling can fail in two ways: the product doesn't exist, or there isn't enough stock. A custom error enum describes both cases, and sell returns Result<u32, ShopError> with the total price on success.
#[derive(Debug)]
enum ShopError {
UnknownItem(String),
NotEnoughStock { name: String, wanted: u32, available: u32 },
}
struct Item {
name: String,
price_cents: u32,
quantity: u32,
}
struct Inventory {
items: Vec<Item>,
}
impl Inventory {
fn sell(&mut self, name: &str, amount: u32) -> Result<u32, ShopError> {
let item = self
.items
.iter_mut()
.find(|i| i.name == name)
.ok_or(ShopError::UnknownItem(name.to_string()))?;
if item.quantity < amount {
return Err(ShopError::NotEnoughStock {
name: name.to_string(),
wanted: amount,
available: item.quantity,
});
}
item.quantity -= amount;
Ok(item.price_cents * amount)
}
}
fn main() {
let mut inv = Inventory {
items: vec![
Item { name: "apple".to_string(), price_cents: 45, quantity: 50 },
Item { name: "bread".to_string(), price_cents: 250, quantity: 8 },
],
};
for (name, amount) in [("apple", 6), ("bread", 10), ("cheese", 1), ("bread", 3)] {
match inv.sell(name, amount) {
Ok(cents) => println!("sold {} {} for {} cents", amount, name, cents),
Err(e) => println!("could not sell {} {}: {:?}", amount, name, e),
}
}
println!("bread left: {}", inv.items[1].quantity);
}sold 6 apple for 270 cents
could not sell 10 bread: NotEnoughStock { name: "bread", wanted: 10, available: 8 }
could not sell 1 cheese: UnknownItem("cheese")
sold 3 bread for 750 cents
bread left: 5
ok_or turns the Option from find into a Result, and ? returns early with the error if the item is missing.
Step 4: Reports with iterators
A shop owner wants answers: What is the total stock worth? What is running low? What is most valuable? Iterators make each report a few lines long.
struct Item {
name: String,
price_cents: u32,
quantity: u32,
}
fn main() {
let items = vec![
Item { name: "apple".to_string(), price_cents: 45, quantity: 44 },
Item { name: "bread".to_string(), price_cents: 250, quantity: 5 },
Item { name: "milk".to_string(), price_cents: 120, quantity: 2 },
Item { name: "coffee".to_string(), price_cents: 899, quantity: 7 },
];
let total: u32 = items.iter().map(|i| i.price_cents * i.quantity).sum();
println!("Total stock value: {} cents", total);
let low: Vec<&str> = items
.iter()
.filter(|i| i.quantity < 6)
.map(|i| i.name.as_str())
.collect();
println!("Low stock: {:?}", low);
let mut by_value: Vec<&Item> = items.iter().collect();
by_value.sort_by(|a, b| (b.price_cents * b.quantity).cmp(&(a.price_cents * a.quantity)));
println!("Most valuable lines:");
for (rank, item) in by_value.iter().take(3).enumerate() {
println!(" {}. {} ({} cents)", rank + 1, item.name, item.price_cents * item.quantity);
}
}Total stock value: 9763 cents
Low stock: ["bread", "milk"]
Most valuable lines:
1. coffee (6293 cents)
2. apple (1980 cents)
3. bread (1250 cents)
Step 5: Putting it all together
Finally, model every action as a Command enum and process a whole day's list of commands. This is the shape of many real programs: read input, turn it into commands, match on each one.
#[derive(Debug)]
enum ShopError {
UnknownItem(String),
NotEnoughStock(String),
}
enum Command {
Add(&'static str, u32, u32),
Sell(&'static str, u32),
Report,
}
struct Item {
name: String,
price_cents: u32,
quantity: u32,
}
struct Inventory {
items: Vec<Item>,
revenue_cents: u32,
}
impl Inventory {
fn new() -> Self {
Inventory { items: Vec::new(), revenue_cents: 0 }
}
fn add(&mut self, name: &str, price_cents: u32, quantity: u32) {
if let Some(item) = self.items.iter_mut().find(|i| i.name == name) {
item.quantity += quantity;
} else {
self.items.push(Item { name: name.to_string(), price_cents, quantity });
}
}
fn sell(&mut self, name: &str, amount: u32) -> Result<u32, ShopError> {
let item = self
.items
.iter_mut()
.find(|i| i.name == name)
.ok_or(ShopError::UnknownItem(name.to_string()))?;
if item.quantity < amount {
return Err(ShopError::NotEnoughStock(name.to_string()));
}
item.quantity -= amount;
let price = item.price_cents * amount;
self.revenue_cents += price;
Ok(price)
}
fn report(&self) {
println!("--- report ---");
for item in &self.items {
let flag = if item.quantity < 5 { " (reorder!)" } else { "" };
println!("{:<7}{:>4}{}", item.name, item.quantity, flag);
}
println!("revenue: ${}.{:02}", self.revenue_cents / 100, self.revenue_cents % 100);
}
fn run(&mut self, cmd: Command) {
match cmd {
Command::Add(name, price, qty) => {
self.add(name, price, qty);
println!("added {} x {}", qty, name);
}
Command::Sell(name, qty) => match self.sell(name, qty) {
Ok(cents) => println!("sold {} x {} for {} cents", qty, name, cents),
Err(ShopError::UnknownItem(n)) => println!("error: we don't sell {}", n),
Err(ShopError::NotEnoughStock(n)) => println!("error: not enough {}", n),
},
Command::Report => self.report(),
}
}
}
fn main() {
let mut shop = Inventory::new();
let day = vec![
Command::Add("apple", 45, 40),
Command::Add("bread", 250, 6),
Command::Add("tea", 399, 10),
Command::Sell("apple", 12),
Command::Sell("bread", 3),
Command::Sell("pizza", 1),
Command::Sell("tea", 11),
Command::Add("bread", 250, 2),
Command::Sell("bread", 4),
Command::Report,
];
for cmd in day {
shop.run(cmd);
}
}added 40 x apple
added 6 x bread
added 10 x tea
sold 12 x apple for 540 cents
sold 3 x bread for 750 cents
error: we don't sell pizza
error: not enough tea
added 2 x bread
sold 4 x bread for 1000 cents
--- report ---
apple 28
bread 1 (reorder!)
tea 10
revenue: $22.90
Ideas to extend the project
- Add a
Command::Remove(name)that deletes a product withVec::retain. - Store items in a
HashMap<String, Item>instead of aVecfor faster lookup (remember to sort the keys before printing). - Implement
std::fmt::DisplayforItemso the report can simply useprintln!("{}", item). - Add a discount command that lowers an item's price by a percentage.
Test yourself
Why does the project store prices as cents in a u32 instead of dollars in an f64?
- Integers print faster
- To avoid floating-point rounding errors with money
f64cannot be stored in a struct- Rust has no decimal point
What does .ok_or(ShopError::UnknownItem(...)) do to the result of find?
- Panics if nothing is found
- Converts
OptionintoResult, using the given error forNone - Returns the first item
- Converts the error into a string
Which format spec right-aligns a value in a field 4 characters wide?
{:<4}{:^4}{:>4}{:04}