TryBugHunt
goScope errorMedium

Bad score in the list is silently dropped instead of reported

BugFind the bug and fix the code

What it should do

parseScores(fields) converts a row of score cells to numbers. If any cell is not a whole number it returns the error "scores must be whole numbers". parseScores(["90", "85"]) returns [90, 85].

What happens instead

parseScores(["90", "x", "70"]) returns [90] with no error.

package main

import (
    "errors"
    "strconv"
)

func parseScores(fields []string) ([]int, error) {
    scores := []int{}
    var err error
    for _, f := range fields {
        n, err := strconv.Atoi(f)
        if err != nil {
            break
        }
        scores = append(scores, n)
    }
    if err != nil {
        return nil, errors.New("scores must be whole numbers")
    }
    return scores, 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

A medium 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)

n, err := inside the loop declares a new err for each iteration, hiding the err declared before the loop. The loop breaks on the bad cell, but the error it saw belongs to the inner variable and is gone. The check after the loop reads the outer err, which was never assigned and is still nil, so a partial list is returned as if it were complete. Declaring err outside a loop only helps if the loop assigns to it with =, not :=.

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/b6d8b6ad-dcdd-4fa5-89a1-6bca70b9b820" title="Debugging challenge: Bad score in the list is silently dropped instead of reported" 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/b6d8b6ad-dcdd-4fa5-89a1-6bca70b9b820">TryBugHunt</a></p>