How to convert the PathBuf to String
As mcarton has already said it is not so simple as not all paths are UTF-8 encoded. But you can use:
p.into_os_string().into_string()
In order to have a fine control of it utilize ?
to send error to upper level or simply ignore it by calling unwrap()
:
let my_str = cwd.into_os_string().into_string().unwrap();
A nice thing about into_string()
is that the error wrap the original OsString
value.
It is not easy on purpose: String
are UTF-8 encoded, but PathBuf
might not be (eg. on Windows). So the conversion might fail.
There are also to_str
and to_string_lossy
methods for convenience. The former returns an Option<&str>
to indicate possible failure and the later will always succeed but will replace non-UTF-8 characters with U+FFFD REPLACEMENT CHARACTER
(which is why it returns Cow<str>
: if the path is already valid UTF-8, it will return a reference to the inner buffer but if some characters are to be replaced, it will allocate a new String
for that; in both case you can then use into_owned
if you really need a String
).