Rust - 特征“StdError”没有为“OsString”实现

Who*_*ing 5 rust

我正在编写一些使用?运算符的 Rust 代码。这是该代码的几行:

fn files() -> Result<Vec<std::string::String>, Box<Error>> {

    let mut file_paths: Vec<std::string::String> = Vec::new();
    ...
    file_paths.push(pathbuf.path().into_os_string().into_string()?);
    ...
    Ok(file_paths)
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我?在 a 上使用Result它,它也会给我以下错误:

`the trait `StdError` is not implemented for `OsString`.
Run Code Online (Sandbox Code Playgroud)

这与 Rust 文档相反,这里指出:

The ? is shorthand for the entire match statements we wrote earlier. In other words, ? applies to a Result value, and if it was an Ok, it unwraps it and gives the inner value. If it was an Err, it returns from the function you're currently in.

我已经确认 pathbuf.path().into_os_string().into_string() 的类型为Result,因为当我删除 时?,我收到以下编译器错误:

expected struct `std::string::String`, found enum `std::result::Result`
Run Code Online (Sandbox Code Playgroud)

(因为 file_paths 是字符串向量,而不是结果)。

这是 Rust 语言或文档的错误吗?

事实上,我尝试了这个,但没有推送到 Vector,而是简单地用 的值初始化一个变量pathbuf.path().into_os_string().into_string()?,并且得到了相同的错误。

har*_*mic 8

OsString::into_string函数有点不寻常。它返回一个Result<String, OsString>- 所以这个Err变体实际上不是一个错误。

如果OsString无法转换为常规字符串,则Err返回包含原始字符串的变体。

不幸的是,这意味着您不能?直接使用该运算符。但是,您可以使用map_err将错误变体映射到实际错误,如下所示:

file_paths.push(
    pathbuf.path()
    .into_os_string()
    .into_string().
    .map_err(|e| InvalidPathError::new(e))?
);
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,InvalidPathError可能是您自己的错误类型。您还可以使用 std 库中的错误类型。