Problem overview
The first version of the Shopping Cart project prints a tiny receipt for one item. You declare three values yourself: the item name Coffee Mug, a price of 12 and a quantity of 3. The program then prints two lines: the item with its quantity, and the total cost.
Coffee Mug x3
Total: $36
The lesson practises variables, arithmetic and building text from pieces. The total is the price multiplied by the quantity, and the two lines are joined with a newline into one string called result, which is printed once at the end.
Approach: compute, format, join, print
The work splits into four small jobs, each stored in its own variable:
- Declare the input data.
- Compute
totalfrom the price and the quantity. - Build each line of the receipt as text with
format!. - Join the lines into
resultand print it.
Splitting the work this way keeps every variable simple, and it is the shape that bigger receipts follow later: compute the numbers, format each row, join, print.
Step by step
- Declare
itemas the text"Coffee Mug", in quotes. - Declare
priceas 12. It is in whole dollars, so a plain integer is enough. - Declare
quantityas 3. - Compute
totalasprice * quantity: one mug's price repeated for each mug. - Build
line1withformat!. The template has a placeholder for the item, then the literalx, then a placeholder for the quantity. - Build
line2the same way: the labelTotal: $followed by a placeholder fortotal. - Join the rows into
result. Anotherformat!puts a newline,\n, betweenline1andline2. - Print
resultwithprintln!, so each row appears on its own line.
The solution in Rust
let item = "Coffee Mug";
let price = 12;
let quantity = 3;
let total = price * quantity;
let line1 = format!("{} x{}", item, quantity);
let line2 = format!("Total: ${}", total);
let result = format!("{}\n{}", line1, line2);
println!("{}", result);
Rust details worth knowing:
- Type inference.
priceandquantityare whole-number literals, so Rust infersi32for them, andtotalis ani32too. Multiplying twoi32values gives ani32. - Text and numbers don't mix with
+. Writing"Total: $" + totalfails withcannot add `{integer}` to `&str`. The+operator isn't how Rust joins text with other values.format!handles any value that can be displayed. - Placeholders fill in order. In
"{} x{}", the first{}takesitemand the second takesquantity. Thexbetween them is literal text, and there is a space before it. $is not special. Only curly braces mean something in a format string, soTotal: ${}prints a dollar sign and then the number.- Immutable by default. None of the variables use
mut, because none of them changes after it is created.
Edge cases and common mistakes
- Spacing. The first row is
Coffee Mug x3, with a space between the name and thexbut none betweenxand the number. The second has one space after the colon, before the dollar sign. - Joining with the newline. The
\ninside the template is what splits the receipt into two rows. Without it,resultwould holdCoffee Mug x3Total: $36on one line. - Other quantities. The code isn't tied to 3: with a quantity of 1 it prints
Coffee Mug x1andTotal: $12. - Wrong operation. Adding price and quantity gives 15, not 36, and still compiles. Check the total against a number you can work out by hand.
- Large values. An
i32tops out at 2,147,483,647. A price of 1,000,000,000 with a quantity of 3 would overflow, which the compiler rejects when the values are constants. This lesson's amounts are tiny.
Testing
- Price 12 and quantity 3 print
Coffee Mug x3andTotal: $36. - Price 12 and quantity 1 print
Coffee Mug x1andTotal: $12. - Price 5 and quantity 0 print
Coffee Mug x0andTotal: $0.
