rust - 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
在这些功能上有所不同
解决方案
我会让? 操作员完成所有工作。
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)
}
推荐阅读
- node.js - sinon:不能存根不存在的自有属性 formatData
- latex - LaTex 未在参考书目中显示 URL
- python - 在 Python 中对整数进行位掩码时不会出现预期输出
- ios - 当我尝试登录或注册我的应用程序时出现 Swift 窗口层次结构错误?
- unity3d - 绘制瓷砖地图时,带有矢量图形图像的统一二维瓷砖不会改变颜色
- solr - Solr 条件高亮:如何用条件高亮?
- laravel-5 - 我可以从 Pusher 调试控制台触发事件,但 Laravel 5.2 没有触发它们
- xpath - 查找评论的位置索引()
- jmeter - 如何在 Jmeter 中每 4 分钟运行一次身份验证线程
- python - 如何使用 PIL 将图像转换为一维数组?