Pattern Matching
ถ้าคุณคิดว่า switch-case ในภาษาอื่นมีประโยชน์แล้ว เจอ match ของ Rust เข้าไปจะทึ่งครับ เพราะมันทำได้มากกว่าแค่เช็คค่าตัวเลข แต่มัน “แกะ” โครงสร้างข้อมูลออกมาได้ด้วย!
match Expression - พื้นฐาน
Section titled “match Expression - พื้นฐาน”Basic match
Section titled “Basic match”โครงสร้างพื้นฐานคือ match ตามด้วยตัวแปร และ “แขน” (Arms) ที่เป็น pattern ให้จับคู่
fn main() { let number = 3;
// ============================================ // match = เช็คค่าเทียบกับ patterns // pattern => ทำอะไร, // ============================================ match number { 1 => println!("One"), // ถ้า number == 1 2 => println!("Two"), // ถ้า number == 2 3 => println!("Three"), // ถ้า number == 3 _ => println!("Other"), // _ = อื่นๆ ทั้งหมด (wildcard) }
// ============================================ // _ (underscore) = match ทุกค่าที่เหลือ // เหมือน default ใน switch-case // ============================================}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google