【问题标题】:Rust - the trait `StdError` is not implemented for `OsString`Rust - 没有为 `OsString` 实现特征`StdError`
【发布时间】:2023-03-29 17:30:01
【问题描述】:

我正在编写一些使用 ? 运算符的 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)
}

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

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

这与 Rust 文档 here 相悖,该文档指出:

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`

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

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

事实上,我在没有推送到 Vector 的情况下尝试了这个,只是简单地用 pathbuf.path().into_os_string().into_string()? 的值初始化了一个变量,我得到了同样的错误。

【问题讨论】:

  • 您要返回的Error 类型是什么? OsString 很可能无法转换成它,因为into_string 在出错的情况下会返回原始的OsString

标签: rust


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 谢谢,不知道这个。下次会检查文档:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 2021-10-22
  • 2020-08-15
  • 2016-05-29
  • 2021-08-20
  • 2022-12-07
相关资源
最近更新 更多