Trait objects in Rust allow you to store values of different types in a collection as long as they all implement a specific trait, enabling dynamic dispatch. You create them by boxing the trait object or using a reference to it, which lets the compiler call the correct method at runtime based on the actual type.
trait Draw {
fn draw(&self);
}
struct Circle;
struct Square;
impl Draw for Circle {
fn draw(&self) { println!("Drawing circle"); }
}
impl Draw for Square {
fn draw(&self) { println!("Drawing square"); }
}
fn main() {
let c = Box::new(Circle);
let s = Box::new(Square);
let shapes: Vec<Box<dyn Draw>> = vec![c, s];
for shape in shapes {
shape.draw();
}
}