简体   繁体   中英

Rust - how can I return error of a different function?

Given two functions like these:

fn foo() -> Result<i32, Box<dyn std::error::Error>> {
    // returns an error if something goes wrong
}

fn bar() -> Result<bool, Box<dyn std::error::Error>> {
   let x = foo(); // could be ok or err
   if x.is_err() {
       return // I want to return whatever error occured in function foo
    }
}

Is it possible to return the exact error that appeared in function foo from function bar ? Also notice, the Result<T, E> enum has different T in these functions

I would just let the ? operator do all the work.

fn foo(a: i32) -> Result<i32, Box<dyn std::error::Error>> {
    if a < 10 {
        // returns an error if something goes wrong
        Err(Box::from("bad value"))
    } else {
        Ok(a + 2)
    }
}

fn bar(a: i32) -> Result<bool, Box<dyn std::error::Error>> {
    let x = foo(a)?;
    Ok(x > 5)
}

fn main() {
    println!("{:?}", bar(2)); //  displays Err("bad value")
    println!("{:?}", bar(12)); // displays Ok(true)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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