如何将 PathBuf 转换为 String

我必须把 PathBuf变量转换成 String来填充我的函数,我的代码是这样的:

let cwd = env::current_dir().unwrap();
let my_str: String = cwd.as_os_str().to_str().unwrap().to_string();
println!("{:?}", my_str);

它工作,但与 cwd.as_os_str…是可怕的。 你有没有更方便的方法或者有什么建议来处理这个问题?

50738 次浏览

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 to_string_lossy0 if you really need a 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.

One way to convert PathBuf to String would be:

your_path.as_path().display().to_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.