Sub topic 2
Static Dispatch with Generics
This chapter assumes you know basic Rust syntax, ownership and borrowing, how to define structs and implement traits, and how trait bounds work. It covers how generic code is compiled, which is the baseline for comparing trait objects later.
Generic functions and trait bounds
A generic function takes a type parameter and uses a trait bound to say what the type must be able to do. The compiler checks the bound once, at the definition.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
}
fn print_area<T: Shape>(s: &T) {
println!("{:.2}", s.area());
}
fn main() {
print_area(&Square(3.0));
print_area(&Circle(1.0));
}This prints 9.00 and then 3.14. The two calls use different concrete types, so they run different code.
Monomorphization
Rust compiles generic code by monomorphization. For each concrete type a generic function is used with, the compiler generates a separate copy with T replaced by that type. In the example, the compiler produces roughly print_area::<Square> and print_area::<Circle>.
Because each copy knows its exact type, the call to s.area() is resolved at compile time. This is static dispatch. The call is a direct call to a known function, and the compiler can inline it.
impl Trait in argument position
impl Trait in argument position is shorthand for an anonymous generic parameter. These two signatures mean the same thing:
trait Shape {
fn area(&self) -> f64;
}
fn print_a<T: Shape>(s: &T) {
println!("{}", s.area());
}
fn print_b(s: &impl Shape) {
println!("{}", s.area());
}The difference is that with impl Shape you cannot name the type, so you cannot write print_b::<Square>(...) with a turbofish. Use an explicit T when you need to name the type or require two arguments to share one type.
What static dispatch gives you
- Speed. Calls are direct and can be inlined, so the optimizer can see through them.
- No pointer indirection. The value can live on the stack, with no
Boxrequired. - Full trait power. Traits with generic methods, associated constants, or methods returning
Selfall work.
What it costs
- Larger binaries. Each concrete type adds another copy of the function. Heavy generic use can increase compile time and code size.
- One type per slot. A type parameter is fixed at compile time. This does not compile:
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 { self.0 * self.0 }
}
impl Shape for Circle {
fn area(&self) -> f64 { self.0 * self.0 * 3.14 }
}
fn make(flag: bool) -> impl Shape {
if flag {
Square(1.0)
} else {
Circle(1.0)
}
}The compiler rejects make with a "mismatched types" error. impl Shape as a return type means "one specific type that I will not name." Both branches must produce that same type. The same limit applies to Vec<T>: every element has the same T.
Common errors
- Missing bound. Calling
s.area()on an unboundedTfails with "no method namedareafound for type parameterT". AddT: Shape. - Mixing types in a
Vec<T>.vec![Square(1.0), Circle(1.0)]fails because the elements have different types. - Over-generic APIs. Making every function generic can bloat code. Generics pay off on hot paths. They matter less elsewhere.
Exercise
Why does fn make(flag: bool) -> impl Shape fail to compile when one branch returns Square and the other returns Circle?
Show answer
An impl Trait return type stands for a single concrete type chosen by the function body. The two branches return different types, so the compiler reports mismatched types. Returning different types chosen at runtime needs a trait object such as Box<dyn Shape>.
Exercise
How many copies of print_area<T: Shape> does the compiler generate if you call it with Square, Circle, and Square again?
Show answer
Two. Monomorphization creates one copy per distinct concrete type, not one per call.