首页 > 解决方案 > 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
    }
}

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

标签: rust

解决方案


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

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)
}

推荐阅读