如何将 PathBuf 转换为 String [英] How to convert the PathBuf to String

查看:33
本文介绍了如何将 PathBuf 转换为 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?

推荐答案

正如 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆