How to convert the PathBuf to String

StringRustDirectoryPath

String Problem Overview


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?

String Solutions


Solution 1 - 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.

Solution 2 - String

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).

Solution 3 - String

One way to convert PathBuf to String would be:

your_path.as_path().display().to_string();

Solution 4 - String

As @mcarton mentioned, to_string_lossy() should do the job.

let cwd = env::current_dir().unwrap();
let path: String =String::from(cwd.to_string_lossy());

rustc 1.56.1 (59eed8a2a 2021-11-01)

I am a (learning) Rust fan (years of c/c++ programmer) but man, if it makes simple thing so complicated, UTF-8 and COW.. makes people lost in the translation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxiaoaiView Question on Stackoverflow
Solution 1 - StringMichele d'AmicoView Answer on Stackoverflow
Solution 2 - StringmcartonView Answer on Stackoverflow
Solution 3 - StringParas BhattraiView Answer on Stackoverflow
Solution 4 - StringypwangView Answer on Stackoverflow