1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| enum Option<T> {
Some(T),
None,
}
impl<T> Option<T> {
pub fn as_ref(&self) -> Option<&T> //从`&Option<T>`转换为`Option<&T>`
pub fn as_mut(&mut self) -> Option<&mut T> //从&mut Option<T>转换为Option<&mut T>
// unwrap: 当遇到None值时会panic
fn unwrap(self) -> T {
match self {
Option::Some(val) => val,
Option::None => panic!("unwrap option None"),
}
}
}
//
fn unwrap_or<T>(option: Option<T>, default: T) -> T {
match option {
None => default,
Some(value) => value,
}
}
//
fn and_then<F, T, A>(option: Option<T>, f: F) -> Option<A>
where F: FnOnce(T) -> Option<A> {
match option {
None => None,
Some(value) => f(value),
}
}
fn ok_or<T, E>(option: Option<T>, err: E) -> Result<T, E> {
match option {
Some(val) => Ok(val),
None => Err(err),
}
}
|