Result
Result
与 Option
相似,但表示操作成功或失败,且每个操作的类型不同。这类似于表达式练习中定义的 Res
,但是一个泛型:Result<T, E>
,其中 T
用于 Ok
变体,E
出现在 Err
变体中。
use std::fs::File; use std::io::Read; fn main() { let file: Result<File, std::io::Error> = File::open("diary.txt"); match file { Ok(mut file) => { let mut contents = String::new(); if let Ok(bytes) = file.read_to_string(&mut contents) { println!("Dear diary: {contents} ({bytes} bytes)"); } else { println!("Could not read file content"); } } Err(err) => { println!("The diary could not be opened: {err}"); } } }
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.