TryBugHunt
rustScope errorMedium

Position of the first negative is always -1

BugFind the bug and fix the code

What it should do

first_negative(values) returns the position of the first negative number in the list, or -1 if there is none. Example: first_negative(&[4, -2, 7]) → 1

What happens instead

first_negative(&[4, -2, 7]) returns -1 instead of 1.

fn first_negative(values: &[i32]) -> i32 {
    let mut index: i32 = -1;
    for index in 0..values.len() {
        if values[index] < 0 {
            break;
        }
    }
    index
}

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 medium 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: for index in ... creates a new loop variable that happens to share the name of the outer index. Inside the loop, index means the loop counter. When the loop ends, that counter goes away, and the outer index, still -1, is what gets returned. break stops the loop but saves nothing.

The fix: Give the loop variable its own name and store the position before breaking: index = i as i32; break;.

Remember: a for loop always declares a fresh variable, even if one with the same name exists outside. To keep a value from inside the loop, assign it to an outer variable explicitly.

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/7d78844f-c616-4bbd-a1b0-b0b8f01e12bd" title="Debugging challenge: Position of the first negative is always -1" 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/7d78844f-c616-4bbd-a1b0-b0b8f01e12bd">TryBugHunt</a></p>