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
- 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. - Create
lineswithVec::new()andlet mut: it starts empty and gains one row per item. - Create
totalwithlet mut, starting at 0. - 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. - Compute
subasprices[i] * quantities[i]. - Add
subtototalwith+=. - Push the item's row with
format!("{} x{}: ${}", ...), passing the name, the quantity and the subtotal in that order. - After the loop, push the total row. It sits outside the braces, so it runs once, not once per item.
- Join the rows into
resultwithlines.join("\n"). - Print
resultwithprintln!.
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 aVec<i32>, and the names are aVec<&str>.linesstarts asVec::new()with no type written; the compiler works outVec<String>from the firstpush. - Indexing uses
usize. The loop variableiis ausize, which is whatitems.len()returns and what vector indexing requires. 0..items.len()excludes the end. The range0..=items.len()would include the length itself, which is one past the last valid index.joinon a vector of strings.lines.join("\n")returns a newStringwith the separator between each two elements.- Loop variable versus
total.totalis 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(). Ifquantitiesis shorter, indexing past its end panics. With two items and one quantity the message readsindex 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,
Mugat price 12 with quantity 0, givesMug x0: $0andTotal: $0. - Empty vectors give
Total: $0.
