TryBugHunt
goScope errorEasy

Retry counter says the first try worked every time

BugFind the bug and fix the code

What it should do

attemptsUntilSuccess(results) counts how many attempts it took to get "ok", or the total number of attempts if none succeeded. attemptsUntilSuccess(["fail", "fail", "ok"]) returns 3.

What happens instead

attemptsUntilSuccess(["fail", "fail", "ok"]) returns 1, and attemptsUntilSuccess(["fail", "fail"]) returns 0.

package main

func attemptsUntilSuccess(results []string) int {
    attempts := 0
    for _, r := range results {
        attempts := attempts + 1
        if r == "ok" {
            return attempts
        }
    }
    return attempts
}

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)

attempts := attempts + 1 inside the loop body creates a new variable on every iteration, initialised from the outer attempts, which is always 0. So the inner value is always 1, and the outer counter never moves. When the loop ends without success, the outer 0 is returned. A counter must be updated with = (or ++) so the change lands on the variable declared outside the loop. If a counter seems stuck at its first value, look for := in the loop.

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/18b56f5e-3f47-4aaf-bd99-3dfef8ba95d4" title="Debugging challenge: Retry counter says the first try worked every time" 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/18b56f5e-3f47-4aaf-bd99-3dfef8ba95d4">TryBugHunt</a></p>