Static vs Dynamic Dispatch
Trade-offs.
Two Ways to Dispatch
When you call a trait method, Rust must decide which concrete implementation runs. There are two strategies: static dispatch (decided at compile time) and dynamic dispatch (decided at runtime).
Static Dispatch With Generics
Generic functions use static dispatch. The compiler generates a specialized copy for each concrete type — a process called monomorphization.
trait Area { fn area(&self) -> f64; }
struct Square { s: f64 }
impl Area for Square { fn area(&self) -> f64 { self.s * self.s } }
fn print_area<T: Area>(shape: &T) {
println!("{}", shape.area());
}
fn main() {
print_area(&Square { s: 4.0 });
}All lessons in this course
- Defining Traits
- Trait Objects and dyn
- Static vs Dynamic Dispatch
- Default Methods