我必须将 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?
推荐答案正如 mcarton 已经说过的,这并不简单,因为并非所有路径都是 UTF-8 编码.但是你可以使用:
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
发布评论