Start learning free

LESSON 194 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 in Rust: Free Shipping with if/else

Practice Read the full explanation

Use an if/else to decide whether to charge shipping based on a free-shipping threshold.

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

let subtotal = 75;
let shipping_cost = 10;
let free_shipping_threshold = 100;

Build:

Subtotal: $75
Shipping: $10
Total: $85

Rules:

  • If subtotal >= free_shipping_threshold, set shipping to 0; otherwise set it to shipping_cost.
  • total = subtotal + shipping.
  • Always include all three lines (Subtotal, Shipping, Total). When shipping is free, the line shows $0: for a subtotal of 120 the lines would be Subtotal: $120, Shipping: $0, Total: $120.
  • Join the three lines with a newline "\n" into one string result, then print it with println!("{}", result).

Decide shipping in an if/else first, then build the three lines.

Declare let mut shipping = 0; before the if, so it is still visible after the if/else, then assign it in both branches.

Use format!("Total: ${}", total) to build each line from a number.

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

STEP 1 OF 14
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V3 in Rust, explained

    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

    1. Declare the three inputs with let: subtotal, shipping_cost and free_shipping_threshold. None of them changes, so none needs mut.
    2. Declare shipping with let mut and start it at 0. It is declared above the if so it is still in scope after the if block ends, and it is mut because the branches assign to it.
    3. Write the if with the condition subtotal >= free_shipping_threshold. Write the closing brace immediately, then fill in the body.
    4. Free case: inside the if, set shipping to 0.
    5. Add the else on the same line as the closing brace of the if, and open its block.
    6. Paid case: inside the else, set shipping to shipping_cost.
    7. Compute total below the if/else as subtotal + shipping.
    8. Build line1, line2 and line3 with format!: a label such as Subtotal: $ followed by a {} placeholder for the number.
    9. Join them into result with one more format! that puts \n between each pair of lines: three lines need two newlines.
    10. Print result with println!.

    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, and shipping takes that type from its first value, 0.
    • The compiler warns about the initial 0. Both branches overwrite shipping before anything reads it, so rustc reports value assigned to `shipping` is never read. It is only a warning, and the program builds and runs. The step asks for the 0 so that the variable exists, with mut, 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 to shipping inside the branches is a compile error, because variables are immutable by default.
    • Declaring shipping inside a branch. A variable created inside the if block disappears at its closing brace, so the later total line 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 \n separators the three rows run together on one line.

    Testing

    These subtotals, with a shipping cost of 10 and a threshold of 100, give:

    SubtotalShipping lineTotal line
    75Shipping: $10Total: $85
    99Shipping: $10Total: $109
    100Shipping: $0Total: $100
    120Shipping: $0Total: $120
    0Shipping: $10Total: $10

    The Subtotal line always repeats the subtotal itself, so a subtotal of 120 prints Subtotal: $120.

    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free