Struct, Enum และ Trait

Rust Pattern Matching with match

Compare a value against values, ranges, tuples and guards, and let the compiler check you covered everything.

  • ระดับกลาง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • match arms
  • Ranges, | and guards
  • if let
match n
0"zero"
1 | 2 | 3"small"
4..=9"medium"
_"large"

The first pattern that fits wins

match compares a value with a list of patterns and runs the first one that fits. Patterns can be single values, several values, ranges, tuples, or a name that catches everything else.

1 | 2 | 3 matches any of the three values and 4..=9 matches a range. n if n < 0 is a guard: the pattern matches only when the condition is true. _ catches everything that is left. if let is a short match for a single pattern.

ประเด็นสำคัญ

  1. 1 | 2 | 3 matches any of the three.
  2. 4..=9 matches a range.
  3. _ catches everything else.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn classify(n: i32) -> &'static str {
    match n {
        0 => "zero",
        1 | 2 | 3 => "small",
        4..=9 => "medium",
        n if n < 0 => "negative",
        _ => "large",
    }
}

fn main() {
    for n in [0, 2, 7, -5, 42] {
        println!("{n}: {}", classify(n));
    }

    let point = (0, 8);
    match point {
        (0, y) => println!("on the y axis at {y}"),
        (x, 0) => println!("on the x axis at {x}"),
        (x, y) => println!("at ({x}, {y})"),
    }

    let maybe = Some(3);
    if let Some(value) = maybe {
        println!("got {value}");
    }
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
0: zero
2: small
7: medium
-5: negative
42: large
on the y axis at 8
got 3

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Temperature Converter →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด