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

查看:145
本文介绍了如何将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所说的那样,并不是所有路径都不都是

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天全站免登陆