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_into
attempts to convert the vector into a fixed-sized array. This can fail:- If the vector has the right size,
Result::Ok
is returned with the array. - Otherwise,
Result::Err
is returned with the original vector.
- If the vector has the right size,