FromUtf8Error
RustERRORNotableString

Invalid UTF-8 in byte vector

Quick Answer

Use from_utf8_lossy for lenient decoding, or validate the source encoding.

What this means

Returned by String::from_utf8() when the byte vector contains invalid UTF-8 sequences.

Why it happens
  1. 1Bytes read from a non-UTF-8 file
  2. 2Binary data received over a socket
  3. 3Wrong text encoding (Latin-1, Windows-1252)

Fix

Lossy conversion

Lossy conversion
let bytes = vec![0x48, 0x65, 0x6c, 0xff]; // 0xFF invalid UTF-8
let s = String::from_utf8_lossy(&bytes);
println!("{}", s); // "Hel�"

Why this works

from_utf8_lossy replaces invalid bytes with the Unicode replacement character.

Code examples
Strictrust
String::from_utf8(bytes)?; // errors on invalid UTF-8
Same error in other languages
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors