trait-concept
Rust Dynamic dispatch
A trait-object reference hides the concrete implementing type from the receiving function. The method is selected through runtime metadata, while Rust still checks the interface statically. Borrowed trait objects do not require heap allocation. Expected output (not executed): 24 12 Why: One signature accepts references to both implementations. Optimization may still devirtualize calls. Common mistake: Equating dynamic dispatch with dynamic typing or mandatory heap allocation.
Formal Syntax & Structure
rust syntaxrust
fn use_item(item: &dyn Trait)Working Example
Example Snippetrust
trait Cost { fn cost(&self) -> u32; }struct Book;struct Pen;impl Cost for Book { fn cost(&self) -> u32 { 12 } }impl Cost for Pen { fn cost(&self) -> u32 { 3 } }fn total(item: &dyn Cost, n: u32) -> u32 { item.cost() * n }fn main() { println!("{} {}", total(&Book, 2), total(&Pen, 4)); }