【问题标题】:Why can't a std::num::ParseIntError be converted into Box<dyn std::error::Error>?为什么不能将 std::num::ParseIntError 转换为 Box<dyn std::error::Error>?
【发布时间】:2021-04-22 01:41:17
【问题描述】:

我正在尝试将字符串解析为整数,并在返回 Result&lt;_, Box&lt;dyn std::error::Error&gt;&gt; 的函数中使用 ? 向上传播解析错误。但是,编译器似乎无法将ParseIntError 转换为必要的Box&lt;dyn std::error::Error&gt;

let res: Result<u32, Box<dyn std::error::Error>> = "0".parse::<u32>();
         ---------------------------------------   ^^^^^^^^^^^^^^^^^^ expected struct `Box`, found struct `ParseIntError`

expected enum `std::result::Result<_, Box<dyn std::error::Error>>`
found enum `std::result::Result<_, ParseIntError>`

但是,我相信这应该可行,因为:

我错过了什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    但是,编译器似乎无法将 ParseIntError 转换为必要的 Box&lt;dyn std::error::Error&gt;

    Rust 不会自动进行这种转换。您的 https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#impl-From%3CE%3E 链接是正确的,但您的代码中的任何内容都不会导致该函数运行。

    此代码需要使用.map_err(|e| e.into());.map_err(From::from);ParseIntError 映射到您的目标Box&lt;dyn std::error::Error&gt; 类型。例如

    let res: Result<u32, Box<dyn std::error::Error>> = "0".parse::<u32>().map_err(|e| e.into());
    

    Rust 通常不会隐式转换值的类型,除了少数情况。例如,如果您改用返回Result&lt;u32, Box&lt;dyn std::error::Error&gt;&gt; 的函数,那么"0".parse::&lt;u32&gt;()?(注意末尾的问号)将自动使用From::from

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多