Skip to content
เข้าสู่ระบบ

Rust Enums

Enum (Enumeration) คือ type ที่กำหนดค่าได้หลายแบบ เป็นหนึ่งใน features ที่ทรงพลังที่สุดของ Rust

Enum ต่างจากภาษาอื่นตรงที่:

  • แต่ละ variant สามารถมี data ต่างกันได้
  • ใช้ร่วมกับ pattern matching ได้อย่างทรงพลัง
  • Compiler ตรวจสอบว่า handle ทุก variant
// Enum พื้นฐาน
enum Direction {
North,
South,
East,
West,
}
// Enum with data
enum 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 เพื่อปลดล็อกบทความทั้งหมด