Hasty Briefsbeta

Bilingual

Using unwrap() in Rust is Okay (2022)

a year ago
  • #Error Handling
  • #Rust
  • #Programming
  • The article discusses the appropriate use of `unwrap()` in Rust programming, emphasizing that it should not be used for error handling in libraries or applications intended for others due to poor user experience.
  • Panics are considered great for debugging as they provide stack traces and line numbers, making bugs easier to diagnose, but they are not suitable for end-user error messages.
  • The author argues that `unwrap()` and `expect()` are acceptable when the programmer can guarantee that the panic will not occur, such as in tests, examples, or when invariants are maintained.
  • Runtime invariants are discussed as conditions that should always be true but are checked at runtime, with examples given on how to handle them either through panics or compile-time checks.
  • The article suggests preferring `expect()` over `unwrap()` for better error messages but acknowledges that `unwrap()` can be used when `expect()` would add unnecessary noise.
  • A critique of the 'recoverable' vs 'unrecoverable' errors dichotomy is presented, advocating for a more concrete approach where panics indicate bugs in the program.
  • The author opposes linting against `unwrap()` entirely, citing its idiomatic use and the impracticality of banning all panicking operations in Rust code.
  • Examples from real-world crates like `aho-corasick` and `regex-syntax` illustrate how runtime invariants and API design influence the decision to panic or handle errors gracefully.