Start learning free

LESSON 167 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 - Free Shipping in Rust

Practice

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

    Shopping Cart V3 in Rust

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