在Rust中,是否可以一次性处理多个不同的错误,而不是单独处理,而不使用额外的功能?简而言之:Rust语句与try-catch语句的等价关系是什么?
像这样的特性(First-class error handling with ?
and catch
)早在2016年就有人提出过,但我不知道它的结果是什么,以及2019年解决这样一个问题的方案可能是什么样子。
例如,做这样的事情:
try {
do_step_1()?;
do_step_2()?;
do_step_3()?;
// etc
} catch {
alert_user("Failed to perform necessary steps");
}
取代:
match do_steps() {
Ok(_) => (),
_ => alert_user("Failed to perform necessary steps")
}
// Additional function:
fn do_steps() -> Result<(), Error>{
do_step_1()?;
do_step_2()?;
do_step_3()?;
// etc
Ok(())
}
我的程序有一个函数,它检查注册表中不同位置的不同数据值,并返回一些聚合数据,它需要使用许多这样的try-cache语句,其中try-catch在循环中,其他try-catch在循环中。
6条答案
按热度按时间1l5u6lss1#
Rust中没有try catch语句,最接近的方法是
?
操作符。但是,您不必创建函数和
match
语句来最终解析它。您可以在作用域中定义闭包,并在闭包中使用?
运算符。然后,throw保存在闭包返回值中,您可以在任何需要的位置捕获它,如下所示:Playground
在Rust中,是否有可能一次性处理多个不同的错误,而不是单独处理,而不使用额外的功能?
在Rust中有一个anyhow板条箱用于错误管理,这是现在最受推荐的。
作为一种替代方案,Rust中有一个failure机箱用于错误管理。使用
Failure
,您可以链接、转换、连接错误。在将错误类型转换为一种常见类型后,您可以轻松捕获(处理)它。e1xvtsh32#
Rust中的
Result
可以使用and_then
链接。因此,您可以执行以下操作:或者如果你想要一个更简洁的语法,你可以用一个宏来实现:
playground
agyaoht73#
还有一个不稳定的特性叫做
try_blocks
(https://doc.rust-lang.org/beta/unstable-book/language-features/try-blocks.html,https://github.com/rust-lang/rust/issues/31436)用法示例:
hgtggwj04#
我认为
match
表达式等效于try/catch
我们尝试从API获取天气报告,如果我们的请求失败,处理错误,否则显示结果。
ghg1uchk5#
不确定这是否被认为是惯用的Rust,但是可以使用匿名闭包来实现类似于
try/catch
的语法:5ssjco0h6#
try
和except
概念的使用非常模糊,因为Rust是强类型语言,用户必须依赖提供的Option<T>
和Result<T, E>
枚举或定义自己习惯的枚举来编写自己的错误处理方法。有关使用枚举进行错误处理的更深入的内容,请参见此处。
try
宏已被弃用,并已被?
操作符所取代,这使得组织和清理错误处理变得更容易,因为它可能会变得混乱。?
操作符的主要用途是,它允许您为Result<T, E>
的Err(E)
变体实现From trait。下面是一个基本示例: