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

Trait Objects Pattern

Patterns สำหรับ dynamic dispatch ใน Rust โดย trait objects ให้ความสามารถในการเก็บ types ต่างๆ ที่ implement trait เดียวกันไว้ใน collection เดียว ทำให้เขียน polymorphic code ได้แม้ Rust จะเป็น statically typed

Trait objects ใช้ dyn keyword เพื่อบอก compiler ว่าต้องการ dynamic dispatch ตัว type จริงจะถูก determine ที่ runtime

การสร้าง trait object ต้องใช้ pointer เช่น Box, & หรือ Rc เพราะ size ไม่รู้ตอน compile time

trait Animal {
fn speak(&self) -> &str;
fn name(&self) -> &str;
}
struct Dog {
name: String,
}
impl Animal for Dog {
fn speak(&self) -> &str { "Woof!" }
fn name(&self) -> &str { &self.name }
}
struct Cat {
name: String,
}
impl Animal for Cat {
fn speak(&self) -> &str { "Meow!" }
fn name(&self) -> &str { &self.name }
}
fn main() {
// Heterogeneous collection - mixed types!
let animals: Vec<Box<dyn Animal>> = vec![
Box::new(Dog { name: "Buddy".to_string() }),
Box::new(Cat { name: "Whiskers".to_string() }),
];
for animal in &animals {
println!("{} says: {}", animal.name(), animal.speak());
}
// Function parameter with trait object
fn greet(animal: &dyn Animal) {
println!("Hello, {}!", animal.name());
}
greet(&Dog { name: "Max".to_string() });
greet(&Cat { name: "Luna".to_string() });
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด