5. struct, enum และ match
สร้างชนิดข้อมูลของตัวเอง
struct: รวมข้อมูลหลายอย่างเป็นก้อนเดียว
struct Product {
name: String,
price: f64,
stock: u32,
}
fn main() {
let mut p = Product {
name: String::from("กาแฟ"),
price: 45.0,
stock: 10,
};
p.stock -= 1;
println!("{} เหลือ {} ชิ้น", p.name, p.stock);
}
impl: ใส่ความสามารถให้ struct
impl Product {
// ฟังก์ชันสร้าง (เรียกว่า associated function) ไม่มี self
fn new(name: &str, price: f64) -> Product {
Product { name: name.to_string(), price, stock: 0 }
}
// method: มี &self = ยืมตัวมันเองมาอ่าน
fn total_value(&self) -> f64 {
self.price * self.stock as f64
}
// &mut self = ยืมตัวมันเองมาแก้
fn restock(&mut self, amount: u32) {
self.stock += amount;
}
}
fn main() {
let mut tea = Product::new("ชาเย็น", 40.0);
tea.restock(5);
println!("มูลค่า {}", tea.total_value()); // 200
}
พิมพ์ struct ออกมาดู
#[derive(Debug)]
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
println!("{:?}", p); // Point { x: 1, y: 2 }
println!("{:#?}", p); // แบบหลายบรรทัด อ่านง่าย
enum: ค่าที่เป็นได้หนึ่งในหลายแบบ
enum Payment {
Cash,
Card(String), // เก็บเลขบัตรไว้ด้วย
Transfer { bank: String, reference: u64 },
}
enum ของ Rust ไม่ใช่แค่รายชื่อ แต่ละแบบเก็บข้อมูลของตัวเองได้ ใช้คู่กับ match:
fn describe(p: &Payment) -> String {
match p {
Payment::Cash => "เงินสด".to_string(),
Payment::Card(number) => format!("บัตร {number}"),
Payment::Transfer { bank, reference } => format!("โอนผ่าน {bank} อ้างอิง {reference}"),
}
}
ถ้าวันหนึ่งเพิ่ม Payment::QrCode คอมไพเลอร์จะชี้ทุก match ที่ยังไม่ได้จัดการแบบใหม่ ไม่มีทางลืม
Option: ค่าที่อาจไม่มี
Rust ไม่มี null ค่าที่อาจไม่มีใช้ Option ซึ่งเป็น enum ธรรมดา:
enum Option<T> { // มีอยู่แล้วในภาษา ไม่ต้องเขียนเอง
Some(T), // มีค่า
None, // ไม่มี
}
fn find_price(name: &str) -> Option<f64> {
match name {
"กาแฟ" => Some(45.0),
"ชา" => Some(40.0),
_ => None,
}
}
fn main() {
match find_price("โกโก้") {
Some(p) => println!("ราคา {p}"),
None => println!("ไม่มีขาย"),
}
// แบบสั้น เมื่อสนใจแค่กรณีที่มีค่า
if let Some(p) = find_price("ชา") {
println!("ชา {p} บาท");
}
// ใช้ค่าสำรองเมื่อไม่มี
let price = find_price("น้ำ").unwrap_or(0.0);
}
เพราะ
Option บังคับให้จัดการกรณี None ก่อนใช้ค่า บั๊กแบบ "NullReferenceException" ที่พบบ่อยในภาษาอื่นจึงแทบไม่เกิดใน Rust- สร้าง
struct Student { name: String, scores: Vec<u32> }พร้อม methodaverage(&self) -> f64 - สร้าง
enum Shape { Circle(f64), Rect(f64, f64) }และฟังก์ชันareaที่ใช้match - เขียนฟังก์ชันหาตัวเลขที่มากที่สุดในรายการ คืน
Option<i32>(รายการว่างคืนNone)