Structured Error Handling with Result

We have already seen the Result enum. This is used pervasively when errors are expected as part of normal operation:

  1. use std::fs::File;
  2. use std::io::Read;
  3. fn main() {
  4. let file = File::open("diary.txt");
  5. match file {
  6. Ok(mut file) => {
  7. let mut contents = String::new();
  8. file.read_to_string(&mut contents);
  9. println!("Dear diary: {contents}");
  10. },
  11. Err(err) => {
  12. println!("The diary could not be opened: {err}");
  13. }
  14. }
  15. }
  • As with Option, the successful value sits inside of Result, forcing the developer to explicitly extract it. This encourages error checking. In the case where an error should never happen, unwrap() or expect() can be called, and this is a signal of the developer intent too.
  • Result documentation is a recommended read. Not during the course, but it is worth mentioning. It contains a lot of convenience methods and functions that help functional-style programming.