给定以下两个功能:
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
返回出现在函数bar
中的确切错误?还要注意,
Result<T, E>
枚举在这些函数中具有不同的T
最佳答案
我只是让? operator完成所有工作。
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)
}
关于rust - Rust-如何返回其他函数的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65988630/