Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. The question mark ? is a sugar syntax ...

  2. eprintln!

  3. Result.expect is a more user friendly alternative to Result.unwrap. Result.expect allows you to define a customized error message. It is suggested that you use Result.expect instead of Result.unwrap where applicable. Of course, both Result.expect and Result.unwrap are discouraged and it is suggested that you use pattern matching and handle errors explicitly.

  4. Result.ok converts a Result object to an Option object. Symetrically, Option.ok_or converts an Option to a Result object.

  5. The recommended way of error handling in Rust is to define an enum that covers meaningful error cases for your library, implement Debug, Display and std::error::Error for that enum. This is fast/cheap (no heap allocation on error), and precise and easy to use.

  6. By default errors in Rust are checked (at compile time). However, you can get unchecked error using Box<dyn std::error::Error + 'static> with Send and Sync.

  7. The disscussion in The state of error handling in the 2018 edition suggests that thiserror (for libraries) + anyhow (for applications) is a good combination.

Rust Crates for Error Handling

thiserror

anyhow

miette

miette is a fancy diagnostic reporting library and protocol for us mere mortals who aren’t compiler hackers.

InvalidSymbol('m')
"m is not a valid symbol for card rank!"
m is not a valid symbol for card rank!
InvalidSymbol('m')
InvalidSymbol('m'): m is not a valid symbol for card rank!
InvalidSymbol('m'): m is not a valid symbol for card rank!
Custom { kind: Other, error: "oh no!" }
Custom { kind: Other, error: "oh no!" }: oh no!
Os { code: 2, kind: NotFound, message: "No such file or directory" }