Dynamic dispatch in Rust works by using the dyn keyword to create a trait object that defers method resolution until runtime. Instead of the compiler knowing the exact type at compile time, it generates a virtual method table (vtable) for the trait, allowing the program to call the correct implementation based on the actual type of the value stored in the pointer.
trait Draw {
fn draw(&self);
}
struct Button;
impl Draw for Button {
fn draw(&self) { println!("Drawing a button"); }
}
fn main() {
let button = Button;
let trait_obj: &dyn Draw = &button;
trait_obj.draw(); // Calls Button's draw at runtime
}