Start learning free

LESSON 195 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Rust: Summing a Cart with a for Loop

Practice Read the full explanation

Use a for loop over parallel vectors to compute a running total across several items.

You start with: an empty editor (no starter code). Declare this data yourself:

let items = vec!["Shirt", "Pants", "Shoes", "Hat"];
let prices = vec![25, 40, 60, 15];
let quantities = vec![2, 1, 1, 3];

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with println!("{}", result).

Use let mut lines = Vec::new(); and let mut total = 0; before the loop, then push each formatted line.

Call lines.join("\n") at the end.

        let items = vec!["Shirt", "Pants", "Shoes", "Hat"];
        let prices = vec![25, 40, 60, 15];
        let quantities = vec![2, 1, 1, 3];
        let mut lines = Vec::new();
        let mut total = 0;
        for i in 0..items.len() {
            let sub = prices[i] * quantities[i];
            total += sub;
            lines.push(format!("{} x{}: ${}", items[i], quantities[i], sub));
        }
        lines.push(format!("Total: ${}", total));
        let result = lines.join("\n");
        println!("{}", result);

STEP 1 OF 12
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Rust, explained

    Problem overview

    Version 4 of the Shopping Cart handles several items. The data sits in three parallel vectors: items (names), prices and quantities. The same position in each vector describes the same item, so index 0 is a Shirt that costs 25 and is bought twice. The program prints one line per item, in the form Name xQ: $subtotal, then a final total:

    Shirt x2: $50
    Pants x1: $40
    Shoes x1: $60
    Hat x3: $45
    Total: $195
    

    An item's subtotal is its price times its quantity, and the total adds up all the subtotals. Everything is joined with newlines into one string, result, and printed.

    Approach: one pass with a running total

    Visit every position once. For each index i, multiply prices[i] by quantities[i], add that to a running total and store the item's text row. After the loop, add the Total row and join the rows.

    Rows are collected in a vector, lines, instead of being printed one by one, because the lesson wants a single result string. join("\n") then puts a newline between rows only, so there is no stray newline at the end.

    Step by step

    1. Create the three vectors with vec!. Keep the item order identical across them, because the index is the only link between a name, its price and its quantity.
    2. Create lines with Vec::new() and let mut: it starts empty and gains one row per item.
    3. Create total with let mut, starting at 0.
    4. Loop over the positions with for i in 0..items.len(). The range runs from 0 up to, but not including, the length, so it visits exactly the valid indices.
    5. Compute sub as prices[i] * quantities[i].
    6. Add sub to total with +=.
    7. Push the item's row with format!("{} x{}: ${}", ...), passing the name, the quantity and the subtotal in that order.
    8. After the loop, push the total row. It sits outside the braces, so it runs once, not once per item.
    9. Join the rows into result with lines.join("\n").
    10. Print result with println!.

    The solution in Rust

            let items = vec!["Shirt", "Pants", "Shoes", "Hat"];
            let prices = vec![25, 40, 60, 15];
            let quantities = vec![2, 1, 1, 3];
            let mut lines = Vec::new();
            let mut total = 0;
            for i in 0..items.len() {
                let sub = prices[i] * quantities[i];
                total += sub;
                lines.push(format!("{} x{}: ${}", items[i], quantities[i], sub));
            }
            lines.push(format!("Total: ${}", total));
            let result = lines.join("\n");
            println!("{}", result);
    

    Rust details worth knowing:

    • Inferred types. vec![25, 40, 60, 15] is a Vec<i32>, and the names are a Vec<&str>. lines starts as Vec::new() with no type written; the compiler works out Vec<String> from the first push.
    • Indexing uses usize. The loop variable i is a usize, which is what items.len() returns and what vector indexing requires.
    • 0..items.len() excludes the end. The range 0..=items.len() would include the length itself, which is one past the last valid index.
    • join on a vector of strings. lines.join("\n") returns a new String with the separator between each two elements.
    • Loop variable versus total. total is declared before the loop; a variable declared inside the braces would be gone after each pass.

    Complexity

    Time: O(n) for n items. The loop body does a fixed amount of work per item, and join copies each row once.

    Space: O(n) for the vector of rows and the final string.

    Tracing the loop

    Printing the state after each pass shows how the running total grows. For the four items above, each pass computes sub and adds it to total:

    i=0 Shirt sub=50 total=50
    i=1 Pants sub=40 total=90
    i=2 Shoes sub=60 total=150
    i=3 Hat sub=45 total=195
    

    The last value of total, 195, is what the final row shows. The loop never prints a total itself. It only accumulates, and the row is built once, after the last pass.

    An iterator version

    Looping over indexes is the plain way to walk parallel vectors, and it is the one this lesson asks for. Rust can also walk several sequences side by side with zip, which avoids indexing, so a mismatched length cannot panic:

    for ((item, price), qty) in items.iter().zip(&prices).zip(&quantities) {
        let sub = price * qty;
        total += sub;
        println!("{} x{}: ${}", item, qty, sub);
    }
    

    On the same data this prints the same four rows, and the total is 195. The trade-off: zip stops at the shortest vector and silently ignores the leftover entries, whereas the indexed loop reports a mismatch with a panic. The index version is also easier to read while the three-vector pattern is new.

    Edge cases and common mistakes

    • Vectors of different lengths. The loop follows items.len(). If quantities is shorter, indexing past its end panics. With two items and one quantity the message reads index out of bounds: the len is 1 but the index is 1.
    • Out of order vectors. Because the index links the vectors, reordering only one of them pairs names with the wrong prices and still compiles.
    • The total row inside the loop. It would print a Total line after every item.
    • Quantity zero. An item with quantity 0 still prints a row: Mug x0: $0.
    • No items. With empty vectors the loop never runs and the output is just Total: $0.
    • Integer size. The values are i32. Very large prices and quantities would overflow, wrapping silently in an optimized build. This lesson's numbers are small.

    Testing

    • The four items above give the five lines shown at the top, ending with Total: $195.
    • One item, Mug at price 12 with quantity 0, gives Mug x0: $0 and Total: $0.
    • Empty vectors give Total: $0.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free