Sub topic 5
Static dispatch and monomorphization
This chapter assumes you can write generic functions with trait bounds, such as fn largest<T: PartialOrd + Copy>. It explains what the compiler does with those functions, and what that costs and gains.
What static dispatch means
When you call a method on a generic type parameter, Rust knows the concrete type at compile time. It can pick the exact function to call before the program runs. This is called static dispatch. The alternative, deciding at run time, is dynamic dispatch with dyn Trait, which a later chapter covers.
Monomorphization
Static dispatch works through monomorphization. The compiler looks at every concrete type a generic function is used with. It then generates a separate, specialized copy of the function for each one.
use std::fmt::Display;
fn announce<T: Display>(value: T) -> String {
format!("Now showing: {value}")
}
fn main() {
println!("{}", announce(42_i32));
println!("{}", announce("hello"));
}announce is called with an i32 and a &str. The compiler produces two functions, roughly equivalent to this hand-written version:
fn announce_i32(value: i32) -> String {
format!("Now showing: {value}")
}
fn announce_str(value: &str) -> String {
format!("Now showing: {value}")
}
fn main() {
println!("{}", announce_i32(42));
println!("{}", announce_str("hello"));
}The generated names are internal. The idea is that no generic code remains at run time.
Trade-offs
Gains:
- No call overhead from lookup. Each call goes straight to a known function, so there is no vtable lookup.
- Inlining. The optimizer can see the concrete body and inline it, which often removes the call entirely.
- Specialization. Each copy is optimized for its own type. For example,
i32arithmetic compiles to plain integer instructions.
Costs:
- Larger binaries. Ten types means ten copies. Large generic functions used with many types can bloat the output.
- Longer compile times. The compiler generates and optimizes every copy.
- One type per generic parameter. In one call,
Tis a single type, so generics cannot hold a mix of types.
A common mistake
Beginners often expect this to compile:
use std::fmt::Display;
fn pick<T: Display>(flag: bool) -> T {
if flag { 1 } else { "one" }
}It fails for two reasons. The caller chooses T, so the body cannot decide to return an i32 or a &str. The two if branches also have different types. Static dispatch requires every path to resolve to one type.
Choosing static dispatch
Use generics with trait bounds by default. They are fast and idiomatic. Consider dyn Trait when you need a heterogeneous collection, when the concrete type is only known at run time, or when binary size matters more than speed.
Exercise
A generic function fn double<T: std::ops::Add<Output = T> + Copy>(x: T) -> T is called once with an i32, once with an f64, and twice more with i32. How many specialized copies does the compiler generate, and why?
Show answer
Two copies, one for i32 and one for f64. Monomorphization creates one copy per distinct concrete type, not one per call, so the repeated i32 calls share a single copy.