如何将PathBuf转换为String [英] How to convert the PathBuf to String
问题描述
我必须将 PathBuf
变量转换为 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);
它可以工作,但是对 cwd.as_os_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?
推荐答案
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()
为了对其进行更好的控制,请使用?
将错误发送到上级,或者通过调用 unwrap()
来忽略它:
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();
关于 into_string()
的一件好事是,错误包装了原始的 OsString
值.
A nice thing about into_string()
is that the error wrap the original OsString
value.
这篇关于如何将PathBuf转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!