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:
panic!
for programming errors (“bugs”)
- proper error propagation and handling with
Result<T, E>
and Option<T>
for expected and recoverable errors
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:
At this point, a None
/Err(_)
value is a programming error and the program is unable to recover from it.
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;
}
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 ... ?
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.
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:
- deliberately distinguish between programming bugs and recoverable errors
- use a “fail fast” approach for programming bugs
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 ;-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…