TryBugHunt
goOtherMedium

Monthly interest never reaches the account balances

BugFind the bug and fix the code

What it should do

addInterest(owners, balances, percent) adds percent interest to each account and returns the new balance for each owner. addInterest(["ana", "ben"], [1000, 200], 10) returns {"ana": 1100, "ben": 220}.

What happens instead

addInterest(["ana", "ben"], [1000, 200], 10) returns {"ana": 1000, "ben": 200}, the balances before interest.

package main

type account struct {
    owner   string
    balance int
}

func addInterest(owners []string, balances []int, percent int) map[string]int {
    accounts := []account{}
    for i, name := range owners {
        accounts = append(accounts, account{owner: name, balance: balances[i]})
    }
    for _, a := range accounts {
        a.balance += a.balance * percent / 100
    }
    result := map[string]int{}
    for _, a := range accounts {
        result[a.owner] = a.balance
    }
    return result
}

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 mutation and copying bugs pattern

Slices that share one backing array, so changing a copy changes the original.

What you'll practise

A medium Go debugging exercise about mutation and copying bugs: slices that share one backing array, so changing a copy changes the original.

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)

In for _, a := range accounts, a is a copy of each struct, not a reference to it. Adding interest to a.balance changes the copy, which is thrown away at the end of the iteration, so the slice never changes. To modify the elements, index into the slice with accounts[i], or store pointers in the slice. Reading through the copy is fine, which is why the final loop that builds the result is correct.

The pattern behind it: mutation and copying bugs.

More mutation and copying 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/e5fe2524-ae62-4b2a-9282-ef39c88f3de5" title="Debugging challenge: Monthly interest never reaches the account balances" 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/e5fe2524-ae62-4b2a-9282-ef39c88f3de5">TryBugHunt</a></p>