Problem overview
The third version of the Shopping Cart project adds a decision. A cart has a subtotal of 75, regular shipping_cost of 10 and a free_shipping_threshold of 100. If the subtotal reaches the threshold, shipping is free; otherwise the customer pays the regular cost. The program prints a three-line receipt:
Subtotal: $75
Shipping: $10
Total: $85
All three lines always appear. When shipping is free, its line shows $0. The lines are joined with a newline into one string, result, and printed once. The earlier versions only computed and formatted values; this one chooses between two values with if/else.
Approach: decide first, then format
The receipt's numbers depend on one fact: how much shipping costs. So the program settles that first, in a variable called shipping, and builds the text afterwards. The total is then simply subtotal + shipping, and it needs no special case: when shipping is 0, the total equals the subtotal.
The test is subtotal >= free_shipping_threshold. It uses "greater than or equal" because a cart that lands exactly on the threshold ships free. With a threshold of 100, a subtotal of 100 gives Shipping: $0 and a subtotal of 99 gives Shipping: $10.
Step by step
- Declare the three inputs with
let:subtotal,shipping_costandfree_shipping_threshold. None of them changes, so none needsmut. - Declare
shippingwithlet mutand start it at 0. It is declared above theifso it is still in scope after theifblock ends, and it ismutbecause the branches assign to it. - Write the
ifwith the conditionsubtotal >= free_shipping_threshold. Write the closing brace immediately, then fill in the body. - Free case: inside the
if, setshippingto 0. - Add the
elseon the same line as the closing brace of theif, and open its block. - Paid case: inside the
else, setshippingtoshipping_cost. - Compute
totalbelow theif/elseassubtotal + shipping. - Build
line1,line2andline3withformat!: a label such asSubtotal: $followed by a{}placeholder for the number. - Join them into
resultwith one moreformat!that puts\nbetween each pair of lines: three lines need two newlines. - Print
resultwithprintln!.
The solution in Rust
let subtotal = 75;
let shipping_cost = 10;
let free_shipping_threshold = 100;
let mut shipping = 0;
if subtotal >= free_shipping_threshold {
shipping = 0;
} else {
shipping = shipping_cost;
}
let total = subtotal + shipping;
let line1 = format!("Subtotal: ${}", subtotal);
let line2 = format!("Shipping: ${}", shipping);
let line3 = format!("Total: ${}", total);
let result = format!("{}\n{}\n{}", line1, line2, line3);
println!("{}", result);
Rust details worth knowing:
- Conditions need no parentheses, but the braces are required, even around a single statement. The condition must be a
bool: Rust never treats a number as true or false. - Type inference. The whole-number literals default to
i32, andshippingtakes that type from its first value, 0. - The compiler warns about the initial 0. Both branches overwrite
shippingbefore anything reads it, sorustcreportsvalue assigned to `shipping` is never read. It is only a warning, and the program builds and runs. The step asks for the0so that the variable exists, withmut, before the branches. $is just a character. In a format string only curly braces are special, so"Total: ${}"prints a dollar sign and then the number.- The last line has no trailing newline in
result.println!adds the final one when it prints.
Tracing the decision
The if/else runs exactly one of its two blocks, never both and never neither. For the starting data, 75 >= 100 is false, so the else block runs and shipping becomes 10. Then total is 75 + 10, which is 85. Run the same program with a subtotal of 120 and the condition is true: the first block runs, shipping stays 0 and the total is 120.
Only the lines that use shipping and total change between those two carts. The Subtotal line and the structure of the receipt are identical, which is why the decision is made first and the text is built afterwards.
A second look at shipping
The two branches assign to the same variable, so shipping is declared once, above the if. That is the pattern to remember for any "pick one of two values" step: declare the variable first, assign it in each branch, and use it afterwards.
Edge cases and common mistakes
- Exactly on the threshold. Writing
>instead of>=would charge 10 for a subtotal of 100, which should ship free. - Forgetting
mut. Without it, assigning toshippinginside the branches is a compile error, because variables are immutable by default. - Declaring
shippinginside a branch. A variable created inside theifblock disappears at its closing brace, so the latertotalline could not see it. - Skipping the line when shipping is free. All three lines are always printed; free shipping prints
Shipping: $0. - Missing newlines. Without the
\nseparators the three rows run together on one line.
Testing
These subtotals, with a shipping cost of 10 and a threshold of 100, give:
| Subtotal | Shipping line | Total line |
|---|---|---|
| 75 | Shipping: $10 | Total: $85 |
| 99 | Shipping: $10 | Total: $109 |
| 100 | Shipping: $0 | Total: $100 |
| 120 | Shipping: $0 | Total: $120 |
| 0 | Shipping: $10 | Total: $10 |
The Subtotal line always repeats the subtotal itself, so a subtotal of 120 prints Subtotal: $120.
