Sub topic 5
Static dispatch and monomorphization
This chapter assumes you can read Rust generics and trait bounds, such as fn largest<T: PartialOrd + Copy>(items: &[T]) -> T. You should also be able to build and run a small program with cargo. Here you will see what the compiler does with a generic function, why that makes the call fast, and what it costs.
What static dispatch means
Dispatch is the step that decides which function body runs when you call a method. With static dispatch, the compiler decides at compile time. The call becomes a direct jump to a known function, with no lookup at run time.
Generic functions with trait bounds use static dispatch. Take this function:
use std::fmt::Display;
fn announce<T: Display>(item: T) -> String {
format!("Now showing: {item}")
}
fn main() {
println!("{}", announce(42_i32));
println!("{}", announce("hello"));
}The source has one announce. The compiler produces more than one machine-code version of it.
Monomorphization
Monomorphization is the process of generating a separate, concrete copy of a generic function for each set of concrete types it is used with. The word means "making single-shaped".
For the program above, the compiler behaves as if you had written this:
fn announce_i32(item: i32) -> String {
format!("Now showing: {item}")
}
fn announce_str(item: &str) -> String {
format!("Now showing: {item}")
}
fn main() {
println!("{}", announce_i32(42));
println!("{}", announce_str("hello"));
}In the first copy, item is an i32, so Display::fmt resolves to the i32 implementation. In the second copy it resolves to the &str implementation. Each copy is optimized on its own terms. The compiler can inline the fmt call, remove dead branches, and use the exact size and layout of the type.
This is why Rust describes generics as a zero-cost abstraction. You do not pay at run time for writing the code once. You pay at compile time and in binary size.
Seeing it in a trait-based example
Static dispatch applies to any method call on a type the compiler knows exactly. Here is a trait with two implementations and a generic caller:
trait Greeter {
fn greet(&self) -> String;
}
struct English;
struct Spanish;
impl Greeter for English {
fn greet(&self) -> String {
String::from("Hello")
}
}
impl Greeter for Spanish {
fn greet(&self) -> String {
String::from("Hola")
}
}
fn welcome<G: Greeter>(g: &G) {
println!("{}, world", g.greet());
}
fn main() {
welcome(&English);
welcome(&Spanish);
}The compiler creates welcome::<English> and welcome::<Spanish>. Inside the first, g.greet() is a direct call to English::greet. Because the target is known, the optimizer can inline it. It may even fold the whole string into the output.
The `impl Trait` forms are also static
The argument form fn welcome(g: &impl Greeter) is shorthand for the generic version above. It is monomorphized in the same way.
The return form fn make() -> impl Greeter also uses static dispatch. The function returns one concrete type. The compiler knows which one, but the caller sees only the trait. This is different from returning Box<dyn Greeter>, which is a different mechanism covered in the trait objects chapter.
trait Greeter {
fn greet(&self) -> String;
}
struct English;
impl Greeter for English {
fn greet(&self) -> String {
String::from("Hello")
}
}
fn make() -> impl Greeter {
English
}
fn main() {
let g = make();
println!("{}", g.greet());
}Costs of monomorphization
Static dispatch is fast at run time. The cost moves elsewhere.
| Cost | Why it happens |
|---|---|
| Longer compile times | The compiler must generate and optimize every copy. |
| Larger binaries | Each distinct set of type arguments adds machine code. This is called code bloat. |
| Instruction cache pressure | Many near-identical copies compete for space in the CPU cache. |
| Slower incremental builds | A change to a widely used generic can force many copies to be rebuilt. |
A function used with 3 types yields 3 copies. A function with two type parameters used with 4 and 5 different types can yield up to 20 copies, because each combination is its own instance. In practice only the combinations you actually use are generated.
Edge cases and gotchas
Instances are created only when used
A generic function that is never called with a concrete type produces no machine code. The compiler still type-checks the generic body against its bounds. Compile errors in generic code therefore appear even if you never call it.
Bounds are the only contract
Inside a generic function, you can call only the methods that the bounds promise. The compiler checks the body once, in generic form, rather than separately for each type. This differs from C++ templates, where the body is checked after substitution.
fn double<T>(x: T) -> T {
x + x
}This fails to compile, because T has no Add bound. The fix is to state it:
use std::ops::Add;
fn double<T: Add<Output = T> + Copy>(x: T) -> T {
x + x
}
fn main() {
println!("{}", double(21));
println!("{}", double(1.5));
}Copy is needed because x + x would otherwise move x twice.
One concrete type per call site
With static dispatch, a single generic parameter is fixed to one type per instance. You cannot put values of different types in one Vec<T>.
trait Greeter {
fn greet(&self) -> String;
}
struct English;
struct Spanish;
impl Greeter for English {
fn greet(&self) -> String {
String::from("Hello")
}
}
impl Greeter for Spanish {
fn greet(&self) -> String {
String::from("Hola")
}
}
fn all_greetings<G: Greeter>(items: &[G]) -> Vec<String> {
items.iter().map(|g| g.greet()).collect()
}
fn main() {
println!("{:?}", all_greetings(&[English, English]));
// all_greetings(&[English, Spanish]); // error: mismatched types
}A mixed collection needs dynamic dispatch, which the next chapter introduces.
Different returns under `impl Trait`
A function returning impl Greeter must return the same concrete type on every path. This is a common error:
trait Greeter {
fn greet(&self) -> String;
}
struct English;
struct Spanish;
impl Greeter for English {
fn greet(&self) -> String {
String::from("Hello")
}
}
impl Greeter for Spanish {
fn greet(&self) -> String {
String::from("Hola")
}
}
fn pick(flag: bool) -> impl Greeter {
if flag {
English
} else {
Spanish // error: `if` and `else` have incompatible types
}
}
fn main() {
println!("{}", pick(true).greet());
}The compiler needs one concrete type to generate code for. Choosing between types at run time is the job of Box<dyn Greeter>.
Reducing bloat
If a generic function is large but only a small part depends on T, move the type-independent work into a non-generic inner function. The standard library uses this pattern.
use std::path::Path;
fn file_len<P: AsRef<Path>>(path: P) -> std::io::Result<u64> {
fn inner(path: &Path) -> std::io::Result<u64> {
Ok(std::fs::metadata(path)?.len())
}
inner(path.as_ref())
}
fn main() {
println!("{:?}", file_len("Cargo.toml").is_ok());
}Only the thin outer wrapper is copied for each P. The body in inner is compiled once.
Choosing between static and dynamic dispatch
| Question | Prefer static dispatch | Prefer dynamic dispatch |
|---|---|---|
| Are all types known at compile time at the call site? | Yes | No |
| Do you need a mixed collection of types? | No | Yes |
| Is the call in a hot loop? | Yes | Only if measured as fine |
| Is binary size a hard limit? | Maybe not | Often yes |
Exercise
The function fn show<T: Display>(x: T) is called with an i32, a String, and a &str in different places in a program. How many machine-code copies of show does the compiler generate, and why? What happens if you call it a second time with another i32?
Show answer
Three copies: show::<i32>, show::<String>, and show::<&str>. Monomorphization generates one copy per distinct concrete type. A second call with an i32 reuses the existing show::<i32> copy, so the count stays at three.
Exercise
Why does fn pick(flag: bool) -> impl Greeter fail to compile when one branch returns English and the other returns Spanish? Name a way to fix it.
Show answer
impl Trait in return position stands for exactly one concrete type, which the compiler needs in order to generate code. The two branches give two different types. Change the return type to Box<dyn Greeter> and box each value, which uses dynamic dispatch. Another fix is to return an enum that implements Greeter and wraps both types.