Printing a path in Rust
The following will print out the full path:
println!("{}", p.display());
Refer to Path::display
for more details.
As you discovered, the "correct" way to print a Path
is via the .display
method, which returns a type that implements Display
.
There is a reason Path
does not implement Display
itself: formatting a path to a string is a lossy operation. Not all operating systems store paths compatible with UTF-8 and the formatting routines are implicitly all dealing with UTF-8 data only.
As an example, on my Linux system a single byte with value 255 is a perfectly valid filename, but this is not a valid byte in UTF-8. If you try to print that Path
to a string, you have to handle the invalid data somehow: .display
will replace invalid UTF-8 byte sequences with the replacement character U+FFFD, but this operation cannot be reversed.
In summary, Path
s should rarely be handled as if they were strings, and so they don't implement Display
to encourage that.