Option 和 Result
这些类型表示可选数据:
fn main() { let numbers = vec![10, 20, 30]; let first: Option<&i8> = numbers.first(); println!("first: {first:?}"); let arr: Result<[i8; 3], Vec<i8>> = numbers.try_into(); println!("arr: {arr:?}"); }
Option和Result的使用范围很广,不局限于标准库。- 相较于
&T,Option<&T>的空间开销为零。 Result是用于实现错误处理的标准类型,我们将在第 3 天的课程中介绍。try_intoattempts to convert the vector into a fixed-sized array. This can fail:- If the vector has the right size,
Result::Okis returned with the array. - Otherwise,
Result::Erris returned with the original vector.
- If the vector has the right size,