Path::new("notes.txt") looks simple because the name starts as text. Programs can also receive paths whose names do not fit in a Rust string. Rust’s Path type handles platform-specific path rules without requiring every path to be UTF-8.
Paths keep operating-system strings
A borrowed Path holds an operating-system string, exposed through as_os_str(). Its owned counterpart, PathBuf, stores an OsString. These types let a program keep working with a path in its original form. They also provide path operations such as finding a file name or joining components. The standard library documentation for Path describes these operations, and the PathBuf documentation describes the owned form.
This distinction matters when code reads a path supplied by the operating system. Converting it to ordinary text adds a requirement that the path itself may never have met. Rust documents that some operating systems accept paths containing non-UTF-8 data. A string created by your program may convert cleanly, while another path your program encounters may not. Path::to_str() checks that requirement and returns Option<&str>.
None reports a text conversion failure
On Unix, the platform-specific OsStrExt::from_bytes method can make an operating-system string from bytes. This example constructs a path containing an invalid UTF-8 byte and shows the result of to_str():
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
let name = OsStr::from_bytes(b"report-\xff.txt");
let path = Path::new(name);
assert!(path.to_str().is_none());
The Unix extension documentation describes from_bytes. The example does not access the filesystem. None concerns conversion to &str; it says nothing about whether a file exists at that path.
What to do
Keep values as Path or PathBuf while handling files. Call to_str() when an interface specifically needs UTF-8 text, and handle its None case. For a message meant for a person, path.display() can print a path with non-Unicode data, although its output may be lossy. to_string_lossy() replaces invalid sequences, so keep the original path when its exact identity matters. These behaviors are documented on Path.

The Campfire
CommentsThanks. Your comment is waiting for the desk. Once it is approved it appears here within about a minute.
Add a comment