TryBugHunt
goOtherMedium

Removal preview also changes the cart it is previewing

BugFind the bug and fix the code

What it should do

previewRemoval(cart, index) returns the cart unchanged and the cart without the item at index, so the shop can show "before" and "after". previewRemoval(["milk", "eggs", "bread"], 0) returns [["milk", "eggs", "bread"], ["eggs", "bread"]].

What happens instead

previewRemoval(["milk", "eggs", "bread"], 0) returns [["eggs","bread","bread"],["eggs","bread"]], so the "before" cart has lost the milk.

package main

func previewRemoval(cart []string, index int) [][]string {
    after := append(cart[:index], cart[index+1:]...)
    return [][]string{cart, after}
}

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)

cart[:index] shares cart's backing array and has room to grow into it, so append writes the remaining items over the original elements. The removal idiom append(s[:i], s[i+1:]...) is meant for removing in place, and it destroys the original order. That is fine when you no longer need the old slice, but here the caller does. Removing the last item happens to append nothing, so that case looks correct. Build the new slice from an empty one when the original must survive.

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/2d98d82a-e158-42e9-a56d-28ef4f2ef6e1" title="Debugging challenge: Removal preview also changes the cart it is previewing" 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/2d98d82a-e158-42e9-a56d-28ef4f2ef6e1">TryBugHunt</a></p>