`OsString`
OsString is an owned string in the platform's encoding. Use it for command-line arguments and paths that may not be valid UTF-8.
Detailed Explanation
String is UTF-8. Operating systems do not all agree. Unix paths and argv are bytes that are usually UTF-8 but not required to be. Windows paths are WTF-16, a superset of UTF-16 that can hold unpaired surrogates. If you force those values through String, you either error or you lose the original bytes and cannot open the file again.
OsString and its borrowed form OsStr are the standard library's answer. std::env::args_os() yields OsString. Path and PathBuf store OsString internally. OsStr::to_str returns Option<&str> and is the honest conversion: None if the value is not UTF-8. to_string_lossy replaces invalid sequences with U+FFFD and is for display, not for round-trips.
On Unix, OsString is a bag of bytes. The std::os::unix::ffi::OsStrExt trait gives you as_bytes and from_bytes. On Windows, OsStringExt gives you encode_wide. Code that needs the raw encoding is therefore already cfg-split, which is correct: the encodings are not the same.
You can build an OsString from a String losslessly, because UTF-8 is valid on every platform Rust supports. The other direction is fallible. A function that takes impl AsRef<Path> is the usual API for file paths; it accepts &str, String, &Path, PathBuf, and OsString.
Comparison and hashing of OsString are defined, so you can key a HashMap with it. Display is lossy if you go through Display / to_string_lossy; Debug shows an escaped form that preserves the fact that the value might not be UTF-8. Logging a path for an operator should use Debug or display() on Path (also lossy) depending on whether you need a round-trip.
When you reach for OsString: environment arguments, environment variables (env::var_os), and any path you did not create yourself. When you reach for String: text you parse, print, or send as JSON. When you reach for PathBuf: the value is a path and you will call path methods (join, extension).
Code Examples
use std::ffi::OsString;
fn main() {
let from_utf8 = OsString::from("config.toml");
println!("{}", from_utf8.to_str().unwrap()); // prints: config.toml
match from_utf8.to_str() {
Some(s) => println!("utf8 {s}"), // prints: utf8 config.toml
None => println!("not utf-8"),
}
}Common Gotchas
`args()` panics or skips on non-UTF-8
`std::env::args()` yields `String` and will panic on invalid Unicode on some platforms. Use `args_os` if you must accept every argument.
`to_string_lossy` is not a round-trip
The replacement character cannot be turned back into the original bytes. Use it for logs, not for `open`.
`Path` is usually the better parameter
Take `impl AsRef<Path>` rather than `OsString` when you will pass the value to `File::open`.
Do not `unwrap` `to_str` on user paths
A real directory can contain a non-UTF-8 name. Treat `None` as a first-class case.