trait-concept

Rust Static dispatch

Static dispatch selects behavior using the concrete type known during compilation. Generic functions often use this form, allowing optimizations such as inlining. A generic abstraction does not guarantee faster code. Expected output (not executed): 24 12 Why: Each call chooses a concrete T. The compiler can determine the corresponding implementation. Common mistake: Believing the trait bound necessarily performs a runtime lookup.

Formal Syntax & Structure

rust syntaxrust
fn use_item<T: Trait>(item: &T)

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<T: Cost>(item: &T, n: u32) -> u32 { item.cost() * n }fn main() { println!("{} {}", total(&Book, 2), total(&Pen, 4)); }
Rust Reference