Sub topic 7
How the compiler compiles generics
This chapter assumes you can write generic functions with trait bounds and know the difference between a type parameter and a trait object. It explains what the compiler does with your generic code and what that costs.
Monomorphization
Rust compiles generic code by copying it for each concrete type you use. This process is called monomorphization ("making single-shaped"). The compiler type-checks the generic function once, then generates a specialized version for every distinct set of type arguments it finds in your program.
fn double<T: std::ops::Add<Output = T> + Copy>(x: T) -> T {
x + x
}
fn main() {
println!("{}", double(21));
println!("{}", double(1.5));
}The program calls double with an i32 and an f64. The compiler produces two functions, double::<i32> and double::<f64>. Each one is ordinary non-generic machine code, as if you had written double_i32 and double_f64 by hand.
Zero-cost abstraction
Generics are called a zero-cost abstraction because you pay nothing at run time. The specialized copies have these properties:
- Calls are resolved at compile time, so there is no vtable lookup (the table of function pointers that trait objects use).
- Values are stored directly, with no boxing.
- The optimizer sees the concrete types, so it can inline
x + xinto a single instruction.
The result is usually as fast as hand-written code for each type.
What you pay instead
The cost moves from run time to build time and binary size.
- Binary size. Every distinct instantiation is a separate copy. A large generic function used with 20 types exists 20 times. This is sometimes called code bloat.
- Compile time. The compiler has to generate and optimize every copy.
- Only used instantiations count. If nothing calls
double::<u8>, it is never generated.
If a large generic function only needs the generic part at the boundary, move the body into a non-generic inner function. This keeps one copy of the heavy code.
use std::path::Path;
fn read_config<P: AsRef<Path>>(path: P) -> std::io::Result<String> {
fn inner(path: &Path) -> std::io::Result<String> {
std::fs::read_to_string(path)
}
inner(path.as_ref())
}
fn main() {
match read_config("missing.toml") {
Ok(text) => println!("{text}"),
Err(e) => println!("error: {:?}", e.kind()),
}
}Callers can pass &str, String, or PathBuf. Only the small wrapper is duplicated for each type, while inner is compiled once. The standard library uses this pattern in functions such as std::fs::read.
Common errors
Rust checks a generic body before any instantiation exists. Inside the function, you can only use what the bounds promise. This code fails even if you would only ever call it with integers:
fn bigger<T>(a: T, b: T) -> T {
if a > b { a } else { b }
}The compiler reports error E0369, "binary operation > cannot be applied to type T". The fix is the bound T: PartialOrd. This differs from C++ templates, which are checked only after substitution.
Two other behaviors catch people out:
- Generic code from another crate is compiled in your crate, because the compiler needs the function body to specialize it. This is one reason generic-heavy dependencies slow builds.
- Dynamic dispatch (
dyn Trait) does not monomorphize. It compiles one copy and calls through a vtable. The next chapter compares the two approaches.
Exercise
A program calls one generic function process<T> with i32, u8, and String. How many compiled copies of process exist, and what do the copies cost?
Show answer
Three copies exist, one per distinct type argument. The cost is paid at compile time and in binary size. There is no run-time penalty, because each copy is ordinary specialized code with static dispatch.