I have to convert the PathBuf
variable to a String
to feed my function. My code is like this:
let cwd = env::current_dir().unwrap(); let my_str: String = cwd.as_os_str().to_str().unwrap().to_string(); println!("{:?}", my_str);
it works but is awful with the cwd.as_os_str…
. Do you have a more convenient method or any suggestions on how to handle it?
Use std::path::Path to create a path and check if it exists.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With