TryBugHunt
rustType errorMedium

Digit sum of 123 comes out as 150

BugFind the bug and fix the code

What it should do

sum_digits(code) adds up the digits in a string of digits, for a simple checksum. Example: sum_digits("123") → 6

What happens instead

sum_digits("123") returns 150 instead of 6.

fn sum_digits(code: &str) -> u32 {
    code.chars().map(|c| c as u32).sum()
}

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 type errors pattern

Integer overflow, truncating casts with as, and types that do not convert the way you expect.

What you'll practise

A medium Rust debugging exercise about type errors: integer overflow, truncating casts with as, and types that do not convert the way you expect.

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: c as u32 gives the character's Unicode code, not the digit it shows. The character '1' has code 49, '2' is 50 and '3' is 51, so the sum is 150. The cast is allowed, so the compiler cannot warn you.

The fix: Convert the character to its digit value with c.to_digit(10), which returns Some(1) for '1'. unwrap_or(0) skips anything that is not a digit.

Remember: a char cast to a number is its code point. Use to_digit(10) to read a digit, or subtract '0' as u32 if you know the char is a digit.

The pattern behind it: type errors.

More type errors 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/f6411fc0-3c28-4cd0-8f90-29767d182766" title="Debugging challenge: Digit sum of 123 comes out as 150" 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/f6411fc0-3c28-4cd0-8f90-29767d182766">TryBugHunt</a></p>