如何在特定字符处拆分 &Path 的最后一个组件?
How do I split the final component of a &Path at a specific character?
我有一个 &Path
,我需要在第一个冒号处将最终组件文件名分成两部分。
我可以将最终组件作为 &OsStr
(path.file_name()
) - 但实际上我对内容做任何事情都有些困难。 documentation 给了我几个选项:
to_str()
或 to_string_lossy()
,如果它不是 UTF-8(无法保证!),要么失败,要么 return 损坏的字符串
to_bytes()
或 to_cstring()
,但自 Rust 1.6 以来它们被标记为已弃用。
- 在底部我看到
impl OsStrExt
和 as_bytes()
方法。 OsStrExt
是 std::os::unix::ffi::OsStrExt
,描述为 "Unix-specific extensions to OsStr
"。然而 std::os::unix 显然是 "Experimental extensions to std for Unix platforms."
我是不是漏掉了更标准的东西?
碰巧我很乐意将此应用程序限制为 Unix,因此 OsStrExt::as_bytes
看起来是目前的最佳选择;但它真的还在试验阶段,还是文档已经过时了?
没有处理文件系统路径的标准方法,因为并非所有平台都具有相同的路径表示和有效性规则。
在基于 Unix 的系统上(Linux、Mac OS X 等),路径是一个不能包含 null 的字节序列 (u8
)字节。 std::os::unix
模块在这些平台上可用。尽管该模块的描述是 "experimental",但大部分都是稳定的,因此稳定的功能保证在未来的 Rust 1.x 版本中仍然可用。
在 Windows NT 上,路径是一系列 16 位字(通常解释为 UTF-16 代码单元),其中可能包含未配对的代理项。在内部,Rust 将这些路径转换为 WTF-8 (which is just UTF-8 with the addition of allowing the encoding of unpaired surrogates, U+D800–U+DFFF). The std::os::windows
module is available on this platform; it's not shown on Rust's documentation website, but if you build the documentation for std
locally, it should be there. The source for this module is here. It provides different OsStrExt
and OsStringExt
traits,使您可以将 OsStr
编码为可能格式错误的 UTF-16 或将可能格式错误的 UTF-16 路径解码为 OsString
,但是不提供对 WTF-8 表示的访问。
我有一个 &Path
,我需要在第一个冒号处将最终组件文件名分成两部分。
我可以将最终组件作为 &OsStr
(path.file_name()
) - 但实际上我对内容做任何事情都有些困难。 documentation 给了我几个选项:
to_str()
或to_string_lossy()
,如果它不是 UTF-8(无法保证!),要么失败,要么 return 损坏的字符串to_bytes()
或to_cstring()
,但自 Rust 1.6 以来它们被标记为已弃用。- 在底部我看到
impl OsStrExt
和as_bytes()
方法。OsStrExt
是std::os::unix::ffi::OsStrExt
,描述为 "Unix-specific extensions toOsStr
"。然而 std::os::unix 显然是 "Experimental extensions to std for Unix platforms."
我是不是漏掉了更标准的东西?
碰巧我很乐意将此应用程序限制为 Unix,因此 OsStrExt::as_bytes
看起来是目前的最佳选择;但它真的还在试验阶段,还是文档已经过时了?
没有处理文件系统路径的标准方法,因为并非所有平台都具有相同的路径表示和有效性规则。
在基于 Unix 的系统上(Linux、Mac OS X 等),路径是一个不能包含 null 的字节序列 (u8
)字节。 std::os::unix
模块在这些平台上可用。尽管该模块的描述是 "experimental",但大部分都是稳定的,因此稳定的功能保证在未来的 Rust 1.x 版本中仍然可用。
在 Windows NT 上,路径是一系列 16 位字(通常解释为 UTF-16 代码单元),其中可能包含未配对的代理项。在内部,Rust 将这些路径转换为 WTF-8 (which is just UTF-8 with the addition of allowing the encoding of unpaired surrogates, U+D800–U+DFFF). The std::os::windows
module is available on this platform; it's not shown on Rust's documentation website, but if you build the documentation for std
locally, it should be there. The source for this module is here. It provides different OsStrExt
and OsStringExt
traits,使您可以将 OsStr
编码为可能格式错误的 UTF-16 或将可能格式错误的 UTF-16 路径解码为 OsString
,但是不提供对 WTF-8 表示的访问。