Result

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

1. use std::fs::File;
2. use std::io::Read;

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

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.