代码之家  ›  专栏  ›  技术社区  ›  Juan Leni

标准错误类型的转换特征通常丢失

  •  0
  • Juan Leni  · 技术社区  · 6 年前

    ? 运算符导致错误。例如,返回类型为 Result<u32, &'static str> 可能会导致如下错误:

    file.read(&mut buffer)?;
    ^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<std::io::Error>` is not implemented for `&str`
    

    函数返回类型和返回错误之间的不匹配需要转换。然而,有时无法获得特征。这使得 操作人员不方便,强行使用 match 等等,很多。

    允许自动转换最常见的std错误类型的典型返回类型是什么?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Boiethios    6 年前

    你要找的类型是 Box<dyn Error> . std::error::Error

    具有多种错误类型的示例:

    use std::{error::Error, fs::File, io::prelude::*};
    
    fn main() -> Result<(), Box<dyn Error>> {
        let mut file = File::create("foo.txt")?; // io::Error
        file.write_all(b"Hello, world!")?; // io::Error
        let _: i32 = "123".parse()?; // fmt::Error
        Ok(())
    }