Conservative model for multiple error handling

Is it possible to do something like this? If not?

#![feature(conservative_impl_trait)]

use std::error::Error;
use std::io::{self, Read};

fn main() {
    if let Err(e) = foo() {
        println!("Error: {}", e);
    }
}

fn foo() -> Result<(), impl Error> {
    let mut buffer = String::new();
    io::stdin().read_to_string(&mut buffer)?;
    let _: i32 = buffer.parse()?;
    Ok(())
}

I get this error:

error[E0282]: type annotations needed
  --> result.rs:12:24
   |
12 | fn foo() -> Result<(), impl Error> {
   |                        ^^^^^^^^^^ cannot infer type for `_`
+4
source share
1 answer

There are two problems here:

  • impl Traitsare resolved to a specific type statically at compile time. Here you are trying to return two different types that implement Error: std::io::Errorand std::num::ParseIntError. Since it impl Traitshould only be allowed for one type at compile time, this cannot be done.

  • ? From::from , , . - impl Trait, , , .

impl Traits . :

  • Box<Error> . From<E> Error, . .
  • , , , From<ErrType> .
+7

Source: https://habr.com/ru/post/1685110/


All Articles