Utf8Error
RustERRORNotableString
Invalid UTF-8 in byte slice
Quick Answer
Use from_utf8_unchecked only when you have verified the bytes are valid UTF-8.
What this means
Returned by std::str::from_utf8() when a &[u8] slice contains invalid UTF-8. Provides the error byte offset.
Why it happens
- 1Byte slice from a non-UTF-8 source
- 2Slice cut mid-character in a multi-byte sequence
Fix
Get error position
Get error position
match std::str::from_utf8(&bytes) {
Ok(s) => println!("{}", s),
Err(e) => {
println!("Invalid UTF-8 at byte {}", e.valid_up_to());
}
}Why this works
valid_up_to() tells you how many bytes were valid, useful for partial decoding.
Code examples
Triggerrust
std::str::from_utf8(&[0xFF, 0xFE])?; // Utf8Error
Sources
Official documentation ↗
Rust std::str
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev