我正在使用 rust-fuse ,它将挂载选项作为 &[&std::ffi::os_str::OsStr] 。看来我应该拆分传入的逗号分隔选项字符串,我正在这样做:

mod fuse {
    use std::ffi::OsStr;

    pub fn mount(options: &[&OsStr]) {}
}

fn example(optstr: &str) {
    let mut options: &[&str] = &[];
    if optstr != "" {
        options = optstr.split(",").collect::<Vec<_>>().as_slice();
    }
    fuse::mount(options)
}

这给出了以下错误:

error[E0308]: mismatched types
  --> src/main.rs:12:17
   |
12 |     fuse::mount(options)
   |                 ^^^^^^^ expected struct `std::ffi::OsStr`, found str
   |
   = note: expected type `&[&std::ffi::OsStr]`
              found type `&[&str]`

我的印象是所有 &str 也是 OsStr ,但我是 Rust 的新手,所以我想这是错误的。

最佳答案

使用 OsStr::new :

use std::ffi::OsStr;

fn main() {
    let a_string: &str = "Hello world";
    let an_os_str: &OsStr = OsStr::new(a_string);
    println!("{:?}", an_os_str);
}

请注意,显式类型规范不是必需的,我只是出于教育目的而将其包含在内。

在您的具体情况下:
let options: Vec<_> = optstr.split(",").map(OsStr::new).collect();
fuse::mount(&options)

然而,实际上很少需要明确地这样做。大多数情况下,函数接受实现 AsRef<OsStr> 的类型。这将使您无需考虑即可传递更多类型。您可能需要考虑询问维护者或向库提交补丁以使其更通用。

关于rust - 从 &str 转换为 OsStr 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34023250/

10-10 22:48