study_example/pattern_match/
pattern_usage_places.rs

1/// 运行结果如下
2/// ```txt
3/// value = 32
4/// ```
5fn match_arm() {
6    let var: Option<i32> = Some(32);
7    match var {
8        Some(value) => println!("value = {value}"),
9        _ => println!("value is ignored."),
10    }
11}
12
13/// 重点在匹配上,运行结果如下
14/// ```txt
15/// Using purple as the background color
16/// ```
17fn if_let_usage() {
18    let favorite_color: Option<&str> = None;
19    let is_tuesday = false;
20    let age: Result<u8, _> = "34".parse();
21    if let Some(color) = favorite_color {
22        println!("Using your favorite color, {color}, as the background.");
23    } else if is_tuesday {
24        println!("tuesday is green day.");
25    } else if let Ok(age) = age {
26        if age > 30 {
27            println!("Using purple as the background color");
28        } else {
29            println!("Using orange as the background color");
30        }
31    } else {
32        println!("Using blue as the background color");
33    }
34}
35
36/// 运行结果如下
37/// ```txt
38/// current pop: 3
39/// current pop: 2
40/// current pop: 1
41/// ```
42fn while_let_loop_usage() {
43    let mut vec_val = vec![1, 2, 3];
44    while let Some(pop) = vec_val.pop() {
45        println!("current pop: {}", pop);
46    }
47}
48
49/// 运行结果为
50/// ```txt
51/// index 0 value a
52/// index 1 value b
53/// index 2 value c
54/// ```
55fn for_loop_usage() {
56    let v = vec!['a', 'b', 'c'];
57    // 使用 enumerate 方法调整迭代器,以便它生成一个值以及该值的索引,并将其放入元组中。生成的第一个值是元组 (0, 'a') 。
58    // 当此值与模式 (index, value) 匹配时, index 将是 0 , value 将是 'a'
59    for (index, value) in v.iter().enumerate() {
60        println!("index {} value {}", index, value);
61    }
62}
63
64pub fn pattern_usage_places_study() {
65    match_arm();
66    if_let_usage();
67    while_let_loop_usage();
68    for_loop_usage();
69}