Day 4:模式匹配進階

學習目標

  • 掌握 match 的各種模式
  • 使用 if let / while let
  • 認識綁定、守衛(guards)

今日重點

match 的各種模式

let x = 5;
match x {
    1 => println!("one"),
    2 | 3 => println!("two or three"),     // 或
    5..=10 => println!("between 5 and 10"), // 範圍
    _ => println!("something else"),
}

解構結構與列舉

struct Point { x: i32, y: i32 }
let p = Point { x: 0, y: 7 };

match p {
    Point { x, y: 0 } => println!("On the x axis at {}", x),
    Point { x: 0, y } => println!("On the y axis at {}", y),
    Point { x, y } => println!("At ({}, {})", x, y),
}

if let 精簡語法

只想處理單一情況時,用 if let 比 match 精簡。

let some_val = Some(3);
if let Some(3) = some_val {
    println!("got 3");
}

守衛(guard)

let num = Some(4);
match num {
    Some(x) if x % 2 == 0 => println!("even number {}", x),
    Some(x) => println!("odd number {}", x),
    None => (),
}

練習

fn main() {
    let coordinates = (2, 3);

    // 1. 用 range 模式判斷座標在 x <= 3 且 y <= 3 的區域
    match coordinates {
        (x @ 0..=3, y @ 0..=3) => println!("in 3x3 box ({},{})", x, y),
        _ => println!("outside"),
    }

    // 2. 用 if let 解開 Option
    let option = Some(42);
    if let Some(v) = option {
        println!("Value: {}", v);
    }
}

自我檢查

  • 會用 |、範圍、_ 等模式
  • 會解構 struct / enum / tuple
  • 知道何時用 if let 取代 match
  • 會寫守衛條件

深入連結

  • The Book 第 18 章「Patterns and Matching」