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
- Look up the code and create
discount. The chaincoupons.get(coupon).copied().unwrap_or(0)does three things:getreturns theOption,copied()turns anOptionholding a reference into one holding the number itself, andunwrap_or(0)yields the number or 0 forNone. - Compute
totalassubtotal - discount. - Build
resultwithformat!("Total: ${}", total). - Print
resultwithprintln!.
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
HashMapcomes from. It lives instd::collections, and a program has to bring it into scope withuse std::collections::HashMap;before using the name. - Why
copied().getreturnsOption<&i32>, a reference into the map. Withoutcopied(),unwrap_or(0)would need a reference as its default, andsubtotal - discountwould be ani32minus a&i32. Copying the number out gives a plainOption<i32>. unwrap_orversusunwrap. Plainunwrap()panics onNone. Withunwrap_or(0)an unknown code is an ordinary case that gives 0.gettakes a reference to the key. The keys are&strandcouponis a&str, so it is passed as is.HashMap::frombuilds 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.
BOGUSgivesTotal: $100, and the empty string givesTotal: $100too. - Case matters. Keys are compared exactly, so
save20is notSAVE20, and it givesTotal: $100. - Discount bigger than the subtotal. The lesson does not clamp the result. With a subtotal of 30 and
SAVE50the output isTotal: $-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
| Subtotal | Coupon | Output |
|---|---|---|
| 100 | SAVE20 | Total: $80 |
| 100 | SAVE10 | Total: $90 |
| 100 | BOGUS | Total: $100 |
| 100 | save20 | Total: $100 |
| 30 | SAVE50 | Total: $-20 |
