TryBugHunt
rustLogic errorMedium

UTF-8 byte index is not a char boundary panic

BugFind the bug and fix the code

What it should do

Extract first 2 characters from header string safely. Example: extract_header_prefix("๐Ÿฆ€ Rust") -> "๐Ÿฆ€ "

What happens instead

panicked at 'byte index 2 is not a char boundary; it is inside '๐Ÿฆ€' (bytes 0..4)'

fn extract_header_prefix(s: &str) -> String {
    // Slicing &s[0..2] cuts through a 4-byte UTF-8 emoji
    if s.len() < 2 {
        s.to_string()
    } else {
        s[0..2].to_string()
    }
}

fn main() {
    println!("{}", extract_header_prefix("๐Ÿฆ€ Rust"));
}

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

The wrong operator, an inverted condition, a formula the right way round but backwards.

What you'll practise

A medium Rust debugging exercise about logic errors: the wrong operator, an inverted condition, a formula the right way round but backwards.

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: In Rust, string slicing s[0..2] operates on byte offsets, not Unicode scalar values. The emoji '๐Ÿฆ€' spans 4 UTF-8 bytes (0..4). Slicing at byte index 2 lands inside the character, triggering a runtime panic.

The fix: Use s.chars().take(2).collect() to slice by Unicode character count rather than byte offsets.

Remember: Rust strings are UTF-8 encoded. Direct byte slicing panics unless the index is guaranteed to be on a character boundary.

The pattern behind it: logic errors.

More logic 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/cc680255-ac36-4188-81f0-5551c005cdda" title="Debugging challenge: UTF-8 byte index is not a char boundary panic" 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/cc680255-ac36-4188-81f0-5551c005cdda">TryBugHunt</a></p>