Result

ResultOption 相似,但表示操作成功或失败,且每个操作的类型不同。这类似于表达式练习中定义的 Res,但是一个泛型:Result<T, E>,其中 T 用于 Ok 变体,E 出现在 Err 变体中。

  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 10 minutes.

  • Option 方法相同,成功值位于 Result 方法内部, 开发者必须显示提取成功值。因此,建议进行错误检查。在绝不应出现错误的情况下, 可以调用 unwrap()expect() 方法,这也是一种开发者意向信号。
  • 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.