如何将 PathBuf 转换为 String

编程入门 行业动态 更新时间:2024-10-14 18:15:49
本文介绍了如何将 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

本文发布于:2023-06-08 21:32:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   PathBuf   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!