On this page
Traits, Generics & Dispatch
Prev: Ownership, Borrowing, Lifetimes & RAII | Up: ownership_and_internals | Next: Enums, Pattern Matching & Error Propagation
Rel: Polymorphism & Dispatch, C Vtables
Ref: The Rust Book — Traits
Tags: #public #prog #rust #internals #traits
Contents
- > Static Dispatch (Monomorphization)
- > Dynamic Dispatch (`dyn Trait` Fat Pointers)
- > Associated Types & The Orphan Rule
Static Dispatch (Monomorphization)
Generic bounds (fn draw<T: Shape>(s: &T) or fn draw(s: &impl Shape)) generate specialized machine code per concrete type at compile time — zero vtable indirection and full inlining:
trait Area {
fn area(&self) -> f64;
}
fn print_area(shape: &impl Area) {
println!("area = {:.2}", shape.area());
}
Dynamic Dispatch (dyn Trait Fat Pointers)
When storing heterogeneous types in one collection (Vec<Box<dyn Area>>), Rust creates a two-word fat pointer (data_ptr, vtable_ptr) for runtime dispatch.
Associated Types & The Orphan Rule
- Use associated types (
type Item;onIterator) when a type has one natural implementation; use generic parameters (trait From<T>) when multiple implementations make sense. - Orphan Rule: you may implement a trait for a type only if either the trait or the type is defined in your own crate (use the newtype pattern
struct Wrapper(Vec<String>);when neither is local).
Linked from
Related notes
- tuts/rust/ownership_and_internals Linked here; links to this page; shared tags: #internals, #prog, #rust
- tuts/rust/ownership_and_internals/enums_pattern_matching_and_errors Linked here; links to this page; shared tags: #internals, #prog, #rust
- tuts/rust/ownership_and_internals/ownership_borrowing_and_lifetimes Linked here; links to this page; shared tags: #internals, #prog, #rust
- tuts/c/pointers_and_memory/function_pointers_and_callbacks Linked here; shared tags: #prog
- tuts/programming/paradigms/object_oriented_programming Linked here; shared tags: #prog
- tuts/rust/ownership_and_internals/unsafe_rust_and_ffi_abi shared tags: #internals, #prog, #rust
- tuts/c/compilation_and_internals shared tags: #internals, #prog
- tuts/c/compilation_and_internals/build_pipeline_and_linking shared tags: #internals, #prog
- tuts/c/compilation_and_internals/error_handling_and_cleanup shared tags: #internals, #prog
- tuts/c/compilation_and_internals/memory_layout_and_abi shared tags: #internals, #prog