且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该避免在生产应用程序中解包吗?

更新时间:2023-11-10 12:53:22

虽然整个错误处理"主题非常复杂并且通常基于意见,但实际上可以在这里回答这个问题,因为 Rust 的哲学相当狭隘.即:

While the whole "error handling"-topic is very complicated and often opinion based, this question can actually be answered here, because Rust has rather narrow philosophy. That is:

  • 恐慌!编程错误(错误")
  • 使用ResultOption 正确传播和处理预期和可恢复错误
  • panic! for programming errors ("bugs")
  • proper error propagation and handling with Result<T, E> and Option<T> for expected and recoverable errors

可以将 unwrap() 视为这两种错误之间的转换(它将可恢复的错误转换为 panic!()代码>).当您在程序中编写 unwrap() 时,您是在说:

One can think of unwrap() as converting between those two kinds of errors (it is converting a recoverable error into a panic!()). When you write unwrap() in your program, you are saying:

此时,None/Err(_) 值是一个编程错误,程序无法从中恢复.

At this point, a None/Err(_) value is a programming error and the program is unable to recover from it.

例如,假设您正在使用 HashMap 并想要插入一个您可能希望稍后更改的值:


For example, say you are working with a HashMap and want to insert a value which you may want to mutate later:

age_map.insert("peter", 21);
// ...

if /* some condition */ {
    *age_map.get_mut("peter").unwrap() += 1;
}

这里我们使用 unwrap(),因为我们可以确定键保存一个值.如果没有,这将是一个编程错误,更重要的是:它不是真正可以恢复的.如果那时键 "peter" 没有值,你会怎么做?再次尝试插入... ?

Here we use the unwrap(), because we can be sure that the key holds a value. It would be a programming error if it didn't and even more important: it's not really recoverable. What would you do when at that point there is no value with the key "peter"? Try inserting it again ... ?

但你可能知道,有一个漂亮的entry API 用于 Rust 标准库中的映射.使用该 API,您可以避免所有那些 unwrap().这几乎适用于所有情况:您可以经常重构代码以避免unwrap()!只有在极少数情况下,它才无路可走.但是,如果您想发出信号,则可以使用它:在这一点上,这将是一个编程错误.

But as you may know, there is a beautiful entry API for the maps in Rust's standard library. With that API you can avoid all those unwrap()s. And this applies to pretty much all situations: you can very often restructure your code to avoid the unwrap()! Only in a very few situation there is no way around it. But then it's OK to use it, if you want to signal: at this point, it would be a programming bug.

最近有一篇关于错误处理"主题的相当流行的博客文章,其结论类似于 Rust 的哲学.它很长但值得一读:错误模型".这是我尝试总结与此问题相关的文章:

There has been a recent, fairly popular blog post on the topic of "error handling" whose conclusion is similar to Rust's philosophy. It's rather long but worth reading: "The Error Model". Here is my try on summarizing the article in relation to this question:

  • 故意区分编程错误可恢复错误
  • 对编程错误使用快速失败"方法

总结:当您确定可恢复错误实际上不可恢复unwrap()/em> 那时.在受影响行上方的评论中解释 为什么?" 的奖励积分 ;-)

In summary: use unwrap() when you are sure that the recoverable error that you get is in fact unrecoverable at that point. Bonus points for explaining "why?" in a comment above the affected line ;-)