TryBugHunt
rustScope errorHard

Top score stays at 0 after the loop

BugFind the bug and fix the code

What it should do

best_score(scores) returns the highest score in a list of non-negative scores, or 0 for an empty list. Example: best_score(&[3, 8, 5]) → 8

What happens instead

best_score(&[3, 8, 5]) returns 0 instead of 8.

fn best_score(scores: &[i32]) -> i32 {
    let mut best: i32 = 0;
    scores.iter().for_each(|&s| {
        let best = best.max(s);
    });
    best
}

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 shadowed binding, or a value borrowed after the scope that owned it has ended.

What you'll practise

A hard Rust debugging exercise about scope and closure bugs: a shadowed binding, or a value borrowed after the scope that owned it has ended.

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)

What went wrong: Inside the closure, let best = best.max(s); reads the outer best but stores the answer in a new variable that is also called best. That new variable exists only for one call of the closure. Because the closure only reads the outer best, Rust captures it by shared reference, and the outer value never changes from 0.

The fix: Assign without let: best = best.max(s);. Now the closure captures best mutably and updates it.

Remember: shadowing with let works the same inside closures as anywhere else. If a value set inside a closure or loop is lost afterwards, look for a let on the same name.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

Related errors

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/d6ea0272-731e-46c4-a45f-4a5684b31be0" title="Debugging challenge: Top score stays at 0 after the loop" 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/d6ea0272-731e-46c4-a45f-4a5684b31be0">TryBugHunt</a></p>