Answer#
A Rust String is always valid UTF-8. A file name is not: Windows names are sequences of 16-bit units that may contain unpaired surrogates, and Unix-like systems (macOS among them) store names as bytes that std does not require to be UTF-8. So Rust has OsStr, OsString, Path and PathBuf for names as the system sees them, and conversions to str return an Option for the case where the name does not fit.
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
fn main() {
// A Windows file name can hold an unpaired UTF-16 surrogate, which has no UTF-8 form.
let wide: Vec<u16> = vec![b'a' as u16, 0xD800, b'.' as u16, b't' as u16];
let name = PathBuf::from(OsString::from_wide(&wide));
println!("to_str(): {:?}", name.to_str());
println!("to_string_lossy(): {}", name.to_string_lossy());
println!("Debug: {:?}", name);
}to_str(): None
to_string_lossy(): a�.t
Debug: "a\u{d800}.t"(The program imports a Windows-only extension trait, so it builds on Windows only; that is why it is a good example of the next topic, conditional compilation.)
Rules:
- Keep
Pathall the way. Read the name from the system as aPath, give it back to the system as aPath(to open, rename, delete). Nothing is lost. - Convert only to display.
to_string_lossy()replaces unrepresentable parts with the replacement character�. Good for a list in a window; wrong for finding the file again, because the name is changed. - Convert to
Stringonly when you must store it, for example in a JSON settings file. Decide the policy: skip such files, show an error, or store the bytes in a form of your own. - Do not
unwrap()to_str(). One odd file name in a folder then crashes your app.
Common mistakes#
- Using
to_string_lossy().to_string()and then opening that string as a path. - Assuming file names are valid text because you only ever saw English ones.
Related questions#
Does this really happen?#
Rarely, but a program that opens users' folders meets all kinds of names, and old archives and downloads are where it shows up.
Sources#
- std::ffi::OsStr: https://doc.rust-lang.org/std/ffi/struct.OsStr.html (read 2026-12-05)
- std::path::Path::to_string_lossy: https://doc.rust-lang.org/std/path/struct.Path.html#method.to_string_lossy (read 2026-12-05)