[Question / Discussion] Why is .unwrap() so heavily discouraged?

63 points G915wdcc142up

It has come to my attention that many Rust developers here tell people to NEVER use .unwrap(), and instead to handle all Results and Options with either the ? or the match statement. However, I have to question this statement because of the following:

Sometimes you want your program to panic during runtime. Sometimes you just want to stop execution when something fails, and for me .unwrap() and .expect() feels perfect for this case when you want this exact behavior. Additionally, you may have a web server that does some logic which is not related to a request and if that Result, for example, returns an Err, then you want to stop execution and panic. Consider the following descriptive examples:

  • You are creating a log file with std::fs::OpenOptions because the end user entered in the program's configuration that they want logging enabled. If creating the file fails what are you gonna do? Obviously you will want the program to panic because this is unexpected back-end behavior.
  • You are converting an Option<T> type to an Option<&T> with .as_ref(). What is the change this could possibly fail if you have already verified that the type is valid?

For both of the random examples listed below I believe that it would be too verbose to use a match or ? because you:

  • have either verified that it will never panic, or;
  • you want it to panic anyway if it fails because it is unexpected behavior and you don't want the program to continue execution if it does indeed fail.

So, with all due respect, could someone explain me why it is so heavily discouraged to use in production code? If you want a more descriptive error can't you just use .expect()?