Problem overview
A shop keeps its orders in a cart. You build two structs that work together:
LineItemis one row of the cart, with aname: String, aprice: f64and aquantity: i32. Its methodsubtotalreturns price times quantity.Cartholds aVec<LineItem>in its fielditems. Its methodaddappends a row, andtotaladds up the subtotals of all rows.
The cart has line items; it isn't one. That relationship is called composition. A Cart is built out of LineItem values and delegates the per-row arithmetic to them.
The driver, already in the starter code, creates an empty cart, checks a subtotal, and prints the total before and after adding a third row. An apple at 5 each, quantity 3, has a subtotal of 15. With bread at 20 each, quantity 3, the total becomes 75. Milk at 10, quantity 2, adds 20 more. The expected output is:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach: each type does its own arithmetic
There are two natural places for the math. The cart could reach into every row and compute price * quantity itself, or each row could report its own subtotal and the cart could sum those. The lesson takes the second route. A row knows its price and quantity, so it is the right place to multiply. The cart only needs to ask each row and add up the answers.
The total isn't stored. It is recomputed from the current rows every time total() is called, so adding an item changes the next total automatically, and an empty cart gives 0 because the sum starts at zero.
Step by step
- Declare
struct LineItemwith fieldsname: String,price: f64andquantity: i32. A price is anf64in case it isn't a whole number, and a quantity is always whole. - Open
impl LineItem. - Write
newtakingname: &str,priceandquantity. The text is borrowed from the caller, as a&str. - Build the struct as the last expression. The field
namebecomesname.to_string(), because the struct must own its text. Forpriceandquantity, the field and the parameter share a name, so writing the name once is enough. - Write
subtotalwith&self, since it only reads. It returnsself.price * self.quantity as f64. The conversion is needed because Rust won't multiply anf64by ani32. - Declare
struct Cartwith the fielditems: Vec<LineItem>. - Open
impl Cart. - Write
Cart::new, returningCart { items: Vec::new() }: a cart with no rows. - Write
addwith&mut selfand anitem: LineItem, and push the item ontoself.items. - Write the signature of
totalwith&self, returning anf64. - Start the sum with
let mut sum = 0.0;. It needsmutbecause the loop changes it. - Loop over
&self.items. The&lets the loop borrow the rows instead of taking them out of the cart. - Add each row's subtotal by calling
item.subtotal(). - Return
sumafter the loop, with noreturnand no semicolon.
The solution in Rust
struct LineItem {
name: String,
price: f64,
quantity: i32,
}
impl LineItem {
fn new(name: &str, price: f64, quantity: i32) -> LineItem {
LineItem {
name: name.to_string(),
price,
quantity,
}
}
fn subtotal(&self) -> f64 {
self.price * self.quantity as f64
}
}
struct Cart {
items: Vec<LineItem>,
}
impl Cart {
fn new() -> Cart {
Cart { items: Vec::new() }
}
fn add(&mut self, item: LineItem) {
self.items.push(item);
}
fn total(&self) -> f64 {
let mut sum = 0.0;
for item in &self.items {
sum += item.subtotal();
}
sum
}
}
fn mainFunction() {
let empty = Cart::new();
println!("Empty: {}", empty.total() as i32);
let apple = LineItem::new("Apple", 5.0, 3);
println!("Subtotal: {}", apple.subtotal() as i32);
let mut cart = Cart::new();
cart.add(apple);
cart.add(LineItem::new("Bread", 20.0, 3));
println!("Total: {}", cart.total() as i32);
cart.add(LineItem::new("Milk", 10.0, 2));
println!("Total: {}", cart.total() as i32);
}
Language details
&strversusString. The parameter borrows text, the field owns it, andto_string()makes the owned copy.- The explicit
as f64. Without it,self.price * self.quantityfails witherror[E0277]: cannot multiply `f64` by `i32`. Rust never converts between number types silently. - Why
for item in &self.items. A plainfor item in self.itemswould move the vector into the loop. Heretotalonly has&self, so it couldn't do that, and even for a cart you own, the cart would be unusable afterwards: the compiler reportsborrow of moved valueif you use it again. Borrowing with&leaves the rows where they are, anditemis a&LineIteminside the loop. addtakes ownership of the item. Aftercart.add(apple), the variableappleis moved into the cart and can't be used again. This is why the driver prints the apple's subtotal before adding it.- Printing with
as i32. The driver converts totals toi32so they print as whole numbers. Anas i32cast truncates toward zero, and it would hide fractions:2.99f64 as i32is2.
Complexity
With n rows in the cart, total visits each row once, so it takes O(n) time and O(1) extra space. add is amortized O(1). Recomputing the total every time costs a pass over the rows, but it can never go out of date.
Edge cases and common mistakes
- Empty cart. The loop doesn't run, so
totalreturns the starting 0.0, and the driver printsEmpty: 0. - Putting the
sumreturn inside the loop. The last line belongs after the closing brace of the loop. Inside it, the function would return after the first row. - Starting the sum at an integer.
let mut sum = 0;would makesuman integer and the addition of anf64would not compile. Write0.0. - Storing the total in a field. A stored total goes stale unless
addupdates it. Computing it on demand avoids the problem. - Fractional prices. With floats, totals can pick up tiny rounding errors. A row of 3 items at 0.1 plus a row of 2 at 19.99 totals
40.279999999999994, and cast withas i32gives40. The lesson's whole-number prices avoid this.
Key takeaways
- Composition means one struct holds others, here a
Vec<LineItem>insideCart. - Let each type compute what it knows best, and let the container combine the results.
- Borrow with
&when you only need to read, use&mut selfto change a struct, and convert between number types withas.
