| > But, since good programs don’t panic, and neither do good programmers, it’s very rare that using unwrap or expect is actually the right thing to do. I respectfully disagree. The assert!() macro is a way to document invariants. It's a bug if a variant is violated. It shouldn't have happened, but if it happens, then there's nothing the user can do except reporting the crash. The unwrap() and expect() method document the invariant that the None and Err() variants shouldn't occur. It's fail fast. You should use error handling only if users would be able to handle the errors. Tell the end user that the file they wanted to open is not readable, for example. Tell the users of your library that an error happened, like a parse error of a config file. And so on. Tell the users what they can fix themselves. A bug in your library or program, that's something different. Fail fast! And Rust panics are perfect for that. |
Using the assert macro in your code is (in my experience) generally bad. If your code is written well, you can never test that code path. Document invariants with tests instead, or better yet with infallible code.