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
couponincoupons. If it is there, its value is thediscount; if it is not (an unknown code), the discount is0. 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 withprintln!("{}", 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);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
