[英]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
?是否可以从 function
bar
返回 function foo
中出现的确切错误? Also notice, the Result<T, E>
enum has different T
in these functions另请注意,
Result<T, E>
枚举在这些函数中具有不同的T
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.