Start learning free

LESSON 196 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Rust: Coupon Codes with HashMap

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

    let subtotal = 100;
    let coupon = "SAVE20";
    let coupons = HashMap::from([("SAVE10", 10), ("SAVE20", 20), ("SAVE50", 50)]);

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with println!("{}", result).

Use coupons.get(coupon).copied().unwrap_or(0): get gives an Option, and unwrap_or(0) supplies the default.

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

    let subtotal = 100;
    let coupon = "SAVE20";
    let coupons = HashMap::from([("SAVE10", 10), ("SAVE20", 20), ("SAVE50", 50)]);

    let discount = coupons.get(coupon).copied().unwrap_or(0);
    let total = subtotal - discount;
    let result = format!("Total: ${}", total);
    println!("{}", result);

STEP 1 OF 4
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Rust, explained

    Problem overview

    Version 5 applies a coupon. The program starts with a subtotal of 100, a coupon code, "SAVE20", and a map, coupons, from each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50. It looks the code up, subtracts the discount and prints one line:

    Total: $80
    

    An unknown code takes nothing off, so its discount is 0 and the line would read Total: $100.

    Approach: a map as a lookup table

    You could compare the code against each name with a chain of if statements, but a HashMap is shorter and scales: adding a coupon means adding one entry, not another branch. The map finds a key without scanning the others.

    The one subtlety is that the code might not be in the map. Rust does not hand back a default or a null for a missing key. get returns an Option: Some(value) when the key exists and None when it does not. The solution turns that into a plain number with a default of 0.

    Step by step

    1. Look up the code and create discount. The chain coupons.get(coupon).copied().unwrap_or(0) does three things: get returns the Option, copied() turns an Option holding a reference into one holding the number itself, and unwrap_or(0) yields the number or 0 for None.
    2. Compute total as subtotal - discount.
    3. Build result with format!("Total: ${}", total).
    4. Print result with println!.

    The solution in Rust

        let subtotal = 100;
        let coupon = "SAVE20";
        let coupons = HashMap::from([("SAVE10", 10), ("SAVE20", 20), ("SAVE50", 50)]);
    
        let discount = coupons.get(coupon).copied().unwrap_or(0);
        let total = subtotal - discount;
        let result = format!("Total: ${}", total);
        println!("{}", result);
    

    Rust details worth knowing:

    • Where HashMap comes from. It lives in std::collections, and a program has to bring it into scope with use std::collections::HashMap; before using the name.
    • Why copied(). get returns Option<&i32>, a reference into the map. Without copied(), unwrap_or(0) would need a reference as its default, and subtotal - discount would be an i32 minus a &i32. Copying the number out gives a plain Option<i32>.
    • unwrap_or versus unwrap. Plain unwrap() panics on None. With unwrap_or(0) an unknown code is an ordinary case that gives 0.
    • get takes a reference to the key. The keys are &str and coupon is a &str, so it is passed as is.
    • HashMap::from builds a map from an array of key-value tuples.

    Other ways to read an Option

    The get(...).copied().unwrap_or(0) chain is short, but the same lookup can be written with match, which spells out both cases:

    let discount = match coupons.get(coupon) {
        Some(d) => *d,
        None => 0,
    };
    

    For SAVE20 this gives 20, and for an unknown code such as NOPE it gives 0, the same as the chain. A shorter variant skips copied() by giving unwrap_or a reference and dereferencing the result: *coupons.get(coupon).unwrap_or(&0). All three forms give the same discounts. The one in the lesson reads left to right and is the form worth practising.

    Edge cases and common mistakes

    • Unknown code. BOGUS gives Total: $100, and the empty string gives Total: $100 too.
    • Case matters. Keys are compared exactly, so save20 is not SAVE20, and it gives Total: $100.
    • Discount bigger than the subtotal. The lesson does not clamp the result. With a subtotal of 30 and SAVE50 the output is Total: $-20.
    • Using unwrap(). It works for a known code, then panics for an unknown one.
    • Forgetting copied(). The subtraction then does not type-check against a reference default.

    Testing

    SubtotalCouponOutput
    100SAVE20Total: $80
    100SAVE10Total: $90
    100BOGUSTotal: $100
    100save20Total: $100
    30SAVE50Total: $-20
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free