Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何将PathBuf转换为字符串_String_Rust_Directory_Path - Fatal编程技术网

String 如何将PathBuf转换为字符串

String 如何将PathBuf转换为字符串,string,rust,directory,path,String,Rust,Directory,Path,我必须将PathBuf变量转换为字符串,以提供函数。我的代码如下: let cwd = env::current_dir().unwrap(); let my_str: String = cwd.as_os_str().to_str().unwrap().to_string(); println!("{:?}", my_str); 它可以工作,但对于cwd.as\u os\u str…来说很糟糕。 您是否有更方便的方法或如何处理它的任何建议?故意不容易:String是UTF-8编码的,但是Pa

我必须将
PathBuf
变量转换为
字符串
,以提供函数。我的代码如下:

let cwd = env::current_dir().unwrap();
let my_str: String = cwd.as_os_str().to_str().unwrap().to_string();
println!("{:?}", my_str);
它可以工作,但对于
cwd.as\u os\u str…
来说很糟糕。
您是否有更方便的方法或如何处理它的任何建议?

故意不容易:
String
是UTF-8编码的,但是
PathBuf
可能不是(例如在Windows上)。因此,转换可能会失败


为方便起见,还有许多方法和步骤。前者返回一个
选项
以指示可能的故障,后者将始终成功,但将用
U+FFFD替换字符替换非UTF-8字符
(这就是为什么它返回
Cow
:如果路径已经是有效的UTF-8,它将返回对内部缓冲区的引用,但如果要替换某些字符,它将为此分配一个新的
字符串
;在这两种情况下,如果您确实需要
字符串,则可以使用该字符串).

正如麦卡顿已经说过的,它并不像所有路径那样简单。但您可以使用:

p.into_os_string().into_string()
为了更好地控制它,请利用
将错误发送到上层,或者通过调用
展开()
忽略错误:


转换为字符串()
的一个好处是错误将原始
OsString
值包装起来。

将PathBuf转换为字符串的一种方法是:


您的路径。as\u path().display().to\u string();

您能在\u-owned()中添加一个关于
Cow
的简短解释和使用
的提示吗
?或者我可以编辑你的答案来添加它吗?非常感谢。@lukas kalbertodt,关于Cow的用法,你可以参考这个博客:我一直在使用它,因为它很方便。你知道它是否在内部使用to_string_lossy()?否则,我想知道它如何在不返回任何可能的错误的情况下进行转换吗?
。as_path()
方法不是文档中所必需的:“它还实现了
Deref
Path
,这意味着
Path
切片上的所有方法也可以在
PathBuf
值上找到。”
let my_str = cwd.into_os_string().into_string().unwrap();