Rust Systems & Tokio (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What are Traits and the difference between Static Dispatch (`impl Trait`) and Dynamic Dispatch (`dyn Trait`)?
senior LevelCode ExampleSystem Design
In Simple Words: Traits define shared behavior (interfaces):
- Static Dispatch (
fn process(item: impl Printable)):- Uses Monomorphization at compile time. The compiler generates a dedicated, specialized copy of the function for each concrete type.
- Zero runtime overhead, inlines functions, but increases binary size.
- Dynamic Dispatch (
fn process(item: &dyn Printable)):- Uses Trait Objects with a vtable (virtual method table) at runtime.
- Slightly slower due to pointer indirection, but allows storing collections of heterogeneous types (
Vec<Box<dyn Widget>>).
text
Static vs Dynamic Dispatch:
Static: process(item: impl Drawable) ──► Compiler generates process_Circle(), process_Square()
Dynamic: process(item: &dyn Drawable) ──► Runtime vtable lookup: item.vtable->draw()