keyword

Rust dyn: use a trait object for dynamic dispatch

A trait object lets code work through a trait without naming the concrete implementing type. The method implementation is chosen at runtime. The trait must be dyn-compatible. Expected output (not executed): Entry Why: The trait-object reference dispatches to Ticket’s implementation. Common mistake: Not every trait can be made into a trait object; generic methods often prevent dyn compatibility.

Formal Syntax & Structure

rust syntaxrust
&dyn Trait; Box<dyn Trait>

Working Example

Example Snippetrust
trait Label { fn label(&self) -> &str; }struct Ticket;impl Label for Ticket { fn label(&self) -> &str { "Entry" } }
fn main() {    let ticket = Ticket;    let item: &dyn Label = &ticket;    println!("{}", item.label());}
Rust Reference