Enums
Enum พื้นฐาน
หัวข้อที่มีชื่อว่า “Enum พื้นฐาน”Enum กำหนดประเภทที่สามารถเป็นหนึ่งในหลาย variant ที่มีชื่อ ในรูปแบบที่เรียบง่ายที่สุดจะคล้ายกับ C enum:
enum Direction { North, South, East, West,}
let heading = Direction::North;แต่ละ variant เข้าถึงด้วย syntax :: เพิ่ม Debug เพื่อแสดงผล enum ด้วย {:?}
Variant ที่พกข้อมูล
หัวข้อที่มีชื่อว่า “Variant ที่พกข้อมูล”enum Shape { Circle(f64), // รัศมี Rectangle(f64, f64), // กว้าง, สูง Triangle(f64, f64, f64), // สามด้าน}คุณสร้าง variant โดยเรียกใช้เหมือนฟังก์ชัน:
let c = Shape::Circle(3.0);let r = Shape::Rectangle(4.0, 5.0);Variant ยังสามารถเก็บ field ที่มีชื่อได้ เหมือน struct:
enum Message { Move { x: i32, y: i32 }, Write(String), Quit,}impl บน Enum
หัวข้อที่มีชื่อว่า “impl บน Enum”คุณสามารถเพิ่ม method ให้กับ enum ได้เช่นเดียวกับที่เพิ่มให้กับ struct — ด้วยบล็อก impl และ match ข้างใน:
impl Shape { fn name(&self) -> &str { match self { Shape::Circle(_) => "Circle", Shape::Rectangle(_, _) => "Rectangle", Shape::Triangle(_, _, _) => "Triangle", } }}Option<T> — Enum ในตัว
หัวข้อที่มีชื่อว่า “Option<T> — Enum ในตัว”Rust ไม่มี null แต่ standard library มี Option<T>:
enum Option<T> { Some(T), None,}Some(value) ห่อหุ้มค่าที่มีอยู่ None แทนการขาดหายของค่า คอมไพเลอร์บังคับให้คุณจัดการทั้งสองกรณีก่อนจะใช้ค่าภายใน ซึ่งกำจัดข้อผิดพลาด null-pointer ณ compile time
#[derive(Debug)]enum Shape { Circle(f64), Rectangle(f64, f64), Triangle(f64, f64, f64),}
impl Shape { fn area(&self) -> f64 { match self { Shape::Circle(r) => std::f64::consts::PI * r * r, Shape::Rectangle(w, h) => w * h, Shape::Triangle(a, b, c) => { let s = (a + b + c) / 2.0; (s * (s - a) * (s - b) * (s - c)).sqrt() } } }
fn name(&self) -> &str { match self { Shape::Circle(_) => "Circle", Shape::Rectangle(_, _) => "Rectangle", Shape::Triangle(_, _, _) => "Triangle", } }}
fn main() { let shapes: Vec<Shape> = vec![ Shape::Circle(3.0), Shape::Rectangle(4.0, 5.0), Shape::Triangle(3.0, 4.0, 5.0), ];
for shape in &shapes { println!("{}: area = {:.2}", shape.name(), shape.area()); }
let maybe: Option<i32> = Some(42); println!("Option: {:?}", maybe); let none: Option<i32> = None; println!("None: {:?}", none);}Compiling…