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
42
43
44
45
46
47
//Option是标准库定义的一种枚举类型
//enum Option<T> {
// Some(T),
// None,
// }
//match 必须匹配所有的情况
//2. 使用方式
fn main() {
let some_number = Some(5);
let some_string = Some(String::from("a string"));
let absent_number: Option<i32> = None;

let x: i32 = 5;
let y: Option<i32> = Some(5);
//不能使用,因为x和y类行不同
//let sum = x + y;
let mut temp = 0;
match y {
Some(i) => {temp = i; }
None => {println!("Do Nothing!");}
}
let sum = x + temp;
println!("sum = {}",sum);
//有时候使用match并不方便,尤其是在只对一种情况处理的情况之下,这个时候可以使用
//if let,这在《通过例子学习Rust》中也有介绍。
//let result = plus_one(y);
//match result {
// Some(i) => println!("Result = {}",result),
// None => println!("Nothing"),
//};
if let Some(value) = plus_one(y) {
println!("value = {}",value);
}
if let Some(value) = plus_one(y) {
println!("value = {}",value);
} else {
println!("do nothing");
}


}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(x) => Some(x+1),
}
}