Trait Objects and Dynamic Dispatch
Trait Objects and Dynamic Dispatch
When heterogeneous collections are required at runtime, use dynamic dispatch via trait objects (dyn Trait):
trait Drawable {
fn draw(&self);
}
struct Button;
impl Drawable for Button {
fn draw(&self) { println!("Drawing button"); }
}
struct Checkbox;
impl Drawable for Checkbox {
fn draw(&self) { println!("Drawing checkbox"); }
}
fn render_all(items: &[Box<dyn Drawable>]) {
for item in items {
item.draw();
}
}
fn main() {
let widgets: Vec<Box<dyn Drawable>> = vec![
Box::new(Button),
Box::new(Checkbox),
];
render_all(&widgets);
}