How to Use Async Traits with Dynamic Dispatch
Use the dyn keyword with a pointer type like Box or & to create a trait object that supports dynamic dispatch for async traits. Define your trait with async methods, then store implementations in a collection using Box<dyn TraitName> to call methods polymorphically at runtime.
use std::future::Future;
trait AsyncDraw {
fn draw(&self) -> Box<dyn Future<Output = ()> + Send>;
}
struct Button;
struct Image;
impl AsyncDraw for Button {
fn draw(&self) -> Box<dyn Future<Output = ()> + Send> {
Box::new(async { /* ... */ })
}
}
impl AsyncDraw for Image {
fn draw(&self) -> Box<dyn Future<Output = ()> + Send> {
Box::new(async { /* ... */ })
}
}
fn run_screen(components: Vec<Box<dyn AsyncDraw>>) {
for component in components {
// component.draw().await; // Requires async context
}
}