How to Use Trait Objects for Dynamic Dispatch

Use the `dyn` keyword with a pointer like `Box` to store different types implementing a common trait in a single collection for dynamic dispatch.

Use trait objects with the dyn keyword to store values of different types that implement a common trait in a single collection. Define a trait for shared behavior, implement it on your types, and store them as Box<dyn Trait> in a vector to call methods dynamically at runtime.

trait Draw {
    fn draw(&self);
}

struct Button;
impl Draw for Button {
    fn draw(&self) { println!("Button"); }
}

struct TextField;
impl Draw for TextField {
    fn draw(&self) { println!("TextField"); }
}

fn main() {
    let screen = vec![
        Box::new(Button) as Box<dyn Draw>,
        Box::new(TextField) as Box<dyn Draw>,
    ];
    for component in screen {
        component.draw();
    }
}