menu_book Course Curriculum (Rust) expand_more
Dynamic Dispatch with dyn Trait
Learn Dynamic Dispatch with dyn Trait in Rust through a focused explanation, a dedicated topic-specific example, an engineering boundary, and a mastery check.
Dynamic Dispatch with dyn Trait is a focused Rust lesson inside Generics and Lifetimes. It teaches how Dynamic Dispatch with dyn Trait expresses reusable behavior while retaining compile-time type guarantees.
Read the example from the construct outward: identify the exact syntax or API named by the lesson, trace the values that enter it, and predict the result before running the code. The example is intentionally different from neighboring lessons so the behavior of Dynamic Dispatch with dyn Trait remains visible instead of being hidden inside a generic demo.
Topic-specific example
trait Render {
fn render(&self) -> String;
}
struct Html;
impl Render for Html {
fn render(&self) -> String { "<p>ok</p>".into() }
}
fn main() {
let renderer: Box<dyn Render> = Box::new(Html);
println!("{}", renderer.render());
}
For Dynamic Dispatch with dyn Trait, keep constraints as narrow as the implementation actually needs so invalid type combinations fail early and valid ones remain reusable.