0PricingLogin
Learn Rust Coding · Lesson

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

  1. Defining Traits
  2. Trait Objects and dyn
  3. Static vs Dynamic Dispatch
  4. Default Methods
← Back to Learn Rust Coding