Use a map as a fast lookup table for coupon discounts.
You start with:
subtotal := 100
coupon := "SAVE20"
coupons := map[string]int{"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 withfmt.Println(result).
Use
discount := coupons[coupon]: Go gives the zero value (0 for an int) when the key is missing.
Use
strconv.Itoa(...) to convert each number to text before concatenating it.
subtotal := 100
coupon := "SAVE20"
coupons := map[string]int{"SAVE10": 10, "SAVE20": 20, "SAVE50": 50}
discount := coupons[coupon]
total := subtotal - discount
result := "Total: $" + strconv.Itoa(total)
fmt.Println(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
