Rust Enums
Enum (Enumeration) คือ type ที่กำหนดค่าได้หลายแบบ เป็นหนึ่งใน features ที่ทรงพลังที่สุดของ Rust
Enum คืออะไร
Section titled “Enum คืออะไร”Enum ต่างจากภาษาอื่นตรงที่:
- แต่ละ variant สามารถมี data ต่างกันได้
- ใช้ร่วมกับ pattern matching ได้อย่างทรงพลัง
- Compiler ตรวจสอบว่า handle ทุก variant
// Enum พื้นฐานenum Direction { North, South, East, West,}
// Enum with dataenum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(u8, u8, u8),}
fn main() { let dir = Direction::North;
// Pattern matching match dir { Direction::North => println!("Going north"), Direction::South => println!("Going south"), Direction::East => println!("Going east"), Direction::West => println!("Going west"), }
let msg = Message::Move { x: 10, y: 20 };
match msg { Message::Quit => println!("Quit"), Message::Move { x, y } => println!("Move to ({}, {})", x, y), Message::Write(text) => println!("Write: {}", text), Message::ChangeColor(r, g, b) => println!("Color: RGB({}, {}, {})", r, g, b), }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google