Start learning free

LESSON 66 OF 69 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Rust: Composing Structs with Vec

Practice Read the full explanation

A shop keeps its orders in a cart. Build two types that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • A struct LineItem with fields name: String, price: f64, quantity: i32.
  • fn new(name: &str, price: f64, quantity: i32) -> LineItem builds one (use name.to_string()).
  • fn subtotal(&self) -> f64 returns self.price * self.quantity as f64.

Cart

  • A struct Cart with one field items: Vec<LineItem>.
  • fn new() -> Cart returns a cart with an empty vector.
  • fn add(&mut self, item: LineItem) pushes the item (&mut self because it changes the cart).
  • fn total(&self) -> f64 returns the sum of the subtotals of all items: start let mut sum = 0.0, loop with for item in &self.items, end with sum (no semicolon).

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

Rust has structs and impl blocks instead of classes. The driver mainFunction() is already in the starter code and prints with as i32 to show whole numbers.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

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);
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write struct LineItem and its impl first, then struct Cart and its impl.

for item in &self.items { sum += item.subtotal(); }

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);
}

STEP 1 OF 23
    Ctrl + Enter to check

    RUST · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Rust, explained

    Problem overview

    A shop keeps its orders in a cart. You build two structs that work together:

    • LineItem is one row of the cart, with a name: String, a price: f64 and a quantity: i32. Its method subtotal returns price times quantity.
    • Cart holds a Vec<LineItem> in its field items. Its method add appends a row, and total adds 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

    1. Declare struct LineItem with fields name: String, price: f64 and quantity: i32. A price is an f64 in case it isn't a whole number, and a quantity is always whole.
    2. Open impl LineItem.
    3. Write new taking name: &str, price and quantity. The text is borrowed from the caller, as a &str.
    4. Build the struct as the last expression. The field name becomes name.to_string(), because the struct must own its text. For price and quantity, the field and the parameter share a name, so writing the name once is enough.
    5. Write subtotal with &self, since it only reads. It returns self.price * self.quantity as f64. The conversion is needed because Rust won't multiply an f64 by an i32.
    6. Declare struct Cart with the field items: Vec<LineItem>.
    7. Open impl Cart.
    8. Write Cart::new, returning Cart { items: Vec::new() }: a cart with no rows.
    9. Write add with &mut self and an item: LineItem, and push the item onto self.items.
    10. Write the signature of total with &self, returning an f64.
    11. Start the sum with let mut sum = 0.0;. It needs mut because the loop changes it.
    12. Loop over &self.items. The & lets the loop borrow the rows instead of taking them out of the cart.
    13. Add each row's subtotal by calling item.subtotal().
    14. Return sum after the loop, with no return and 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

    • &str versus String. The parameter borrows text, the field owns it, and to_string() makes the owned copy.
    • The explicit as f64. Without it, self.price * self.quantity fails with error[E0277]: cannot multiply `f64` by `i32`. Rust never converts between number types silently.
    • Why for item in &self.items. A plain for item in self.items would move the vector into the loop. Here total only has &self, so it couldn't do that, and even for a cart you own, the cart would be unusable afterwards: the compiler reports borrow of moved value if you use it again. Borrowing with & leaves the rows where they are, and item is a &LineItem inside the loop.
    • add takes ownership of the item. After cart.add(apple), the variable apple is 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 to i32 so they print as whole numbers. An as i32 cast truncates toward zero, and it would hide fractions: 2.99f64 as i32 is 2.

    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 total returns the starting 0.0, and the driver prints Empty: 0.
    • Putting the sum return 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 make sum an integer and the addition of an f64 would not compile. Write 0.0.
    • Storing the total in a field. A stored total goes stale unless add updates 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 with as i32 gives 40. The lesson's whole-number prices avoid this.

    Key takeaways

    • Composition means one struct holds others, here a Vec<LineItem> inside Cart.
    • 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 self to change a struct, and convert between number types with as.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free