Result

Result is similar to Option, but indicates the success or failure of an operation, each with a different enum variant. It is generic: Result<T, E> where T is used in the Ok variant and E appears in the Err variant.

  1. use std::fs::File;
  2. use std::io::Read;
  3. fn main() {
  4.     let file: Result<File, std::io::Error> = File::open("diary.txt");
  5.     match file {
  6.         Ok(mut file) => {
  7.             let mut contents = String::new();
  8.             if let Ok(bytes) = file.read_to_string(&mut contents) {
  9.                 println!("Dear diary: {contents} ({bytes} bytes)");
  10.             } else {
  11.                 println!("Could not read file content");
  12.             }
  13.         }
  14.         Err(err) => {
  15.             println!("The diary could not be opened: {err}");
  16.         }
  17.     }
  18. }

This slide should take about 5 minutes.

  • 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.
  • Result is the standard type to implement error handling as we will see on Day 4.