While all--topic error handling is very complex and often opinion based, this question can actually be answered here because Rust has a rather narrow philosophy. I.e:
panic! for programming errors ("errors")- correct propagation and error handling with
Result<T, E> and Option<T> for expected and recoverable errors
You might think of unwrap() as a conversion between these two types of errors (it converts the error being restored to panic!() ). When you write unwrap() in your program, you say:
At this point, the value None / Err(_) is a programming error, and the program cannot restore it.
For example, let's say that you are working with a HashMap and want to insert a value that you might want to change later:
age_map.insert("peter", 21); // ... if /* some condition */ { *age_map.get_mut("peter").unwrap() += 1; }
Here we use unwrap() , because we can be sure that the key stores the value. It would be a programming error if it were not so and even more important: it is not restored. What would you do when at this moment there is no value with the key "peter" ? Try pasting it again ...?
But, as you know, there is a beautiful entry API for maps in the Rust standard library. Using this API, you can avoid all these unwrap() s. And this applies to almost all situations: you can very often restructure your code to avoid unwrap() ! Only in very few situations around this is not. But then it is OK to use it if you want to signal: at the moment this will be a programming error.
Recently, a rather popular blog post appeared on the topic "error handling", whose conclusion is similar to the philosophy of Rust. This is quite a long time, but it is worth reading: "Error Model . " Here is my attempt to summarize an article on this subject:
- deliberately distinguish between programming errors and error recovery
- use the fail fast method to program errors.
In conclusion : use unwrap() when you are sure that the error you are recovering is not actually being restored at this point. Bonus points for explaining why? in the comment above the affected line ;-)
Lukas Kalbertodt
source share