Rust - 如何返回不同函数的错误?

Ach*_*113 1 rust

给定两个这样的函数:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以foo从 function返回函数中出现的确切错误bar?另请注意,枚举在这些功能上Result<T, E>有所不同T

pro*_*-fh 6

我会让?操作员完成所有工作。

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)
}
Run Code Online (Sandbox Code Playgroud)