简体   繁体   English

Rust - 没有为 `OsString` 实现特征`StdError`

[英]Rust - the trait `StdError` is not implemented for `OsString`

I'm writing some Rust code which uses the ?我正在写一些 Rust 代码它使用? operator.操作员。 Here is a few lines of that code:这是该代码的几行:

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)
}

However, even though I'm using ?但是,即使我正在使用? on a Result it is giving me the following error:Result上它给了我以下错误:

`the trait `StdError` is not implemented for `OsString`.

This is contrary to the Rust documentation here , which states that:这与此处的 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.

I've confirmed that pathbuf.path().into_os_string().into_string() is of type Result , because when I remove the ?我已经确认 pathbuf.path().into_os_string().into_string() 是Result类型,因为当我删除? , I get the following compiler error: ,我得到以下编译器错误:

expected struct `std::string::String`, found enum `std::result::Result`

(since file_paths is a Vector of strings, not Results). (因为 file_paths 是字符串向量,而不是结果)。

Is this a bug with the Rust language or documentation?这是 Rust 语言或文档的错误吗?

In fact I tried this without pushing to the Vector, but simply initializing a variable with the value of pathbuf.path().into_os_string().into_string()?事实上,我没有推送到 Vector,而是简单地用pathbuf.path().into_os_string().into_string()?的值初始化了一个变量。 , and I got the same error. ,我得到了同样的错误。

The function OsString::into_string is a little unusual. function OsString::into_string有点不寻常。 It returns a Result<String, OsString> - so the Err variant is actually not an error.它返回一个Result<String, OsString> - 所以Err变体实际上不是错误。

In the event that the OsString cannot be converted into a regular string, then the Err variant is returned, containing the original string.如果无法将OsString转换为常规字符串,则返回Err变体,其中包含原始字符串。

Unfortunately this means you cannot use the ?不幸的是,这意味着您不能使用? operator directly.直接运营商。 However, you can use map_err to map the error variant into an actual error, like this:但是,您可以使用map_err将 map 的错误变体变成实际的错误,如下所示:

file_paths.push(
    pathbuf.path()
    .into_os_string()
    .into_string().
    .map_err(|e| InvalidPathError::new(e))?
);

In the above example, InvalidPathError might be your own error type.在上面的示例中, InvalidPathError可能是您自己的错误类型。 You could also use an error type from the std library.您还可以使用 std 库中的错误类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM