Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the PathBuf to String

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?

like image 998
xiaoai Avatar asked May 23 '16 10:05

xiaoai


People also ask

How do you find the file path in Rust?

Use std::path::Path to create a path and check if it exists.


1 Answers

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.

like image 178
Michele d'Amico Avatar answered Sep 22 '22 00:09

Michele d'Amico