Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...