TryBugHunt
goScope errorEasy

Coupon is accepted but the total stays the same

BugFind the bug and fix the code

What it should do

applyCoupon(total, coupon) handles coupons like "SAVE20", which take 20 off the total (never below 0). Other coupon text is ignored. applyCoupon(100, "SAVE20") returns 80.

What happens instead

applyCoupon(100, "SAVE20") returns 100.

package main

import (
    "errors"
    "strconv"
    "strings"
)

func applyCoupon(total int, coupon string) (int, error) {
    if strings.HasPrefix(coupon, "SAVE") {
        amount, err := strconv.Atoi(strings.TrimPrefix(coupon, "SAVE"))
        if err != nil {
            return 0, errors.New("invalid coupon")
        }
        total := total - amount
        if total < 0 {
            total = 0
        }
    }
    return total, nil
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the scope and closure bugs pattern

A variable redeclared with := so the outer one never changes, and loop variables captured late.

What you'll practise

An easy Go debugging exercise about scope and closure bugs: a variable redeclared with := so the outer one never changes, and loop variables captured late.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

total := total - amount declares a new variable called total inside the if block. On the right-hand side, total still means the parameter, so the new variable gets the right value, and the < 0 check runs on it too. But the return statement is outside the block, where total is the untouched parameter. The difference between := and = is one character, and both compile here. Inside a block, use = for anything you mean to update in the outer scope.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/8e0e7d79-cfd5-4f15-8b6b-651eef688db5" title="Debugging challenge: Coupon is accepted but the total stays the same" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/8e0e7d79-cfd5-4f15-8b6b-651eef688db5">TryBugHunt</a></p>