Rust Reference ยท Concepts
Generics and monomorphization in Rust
Reference for Rust generics: how the compiler monomorphizes generic functions and types per concrete type, what it costs, trait bounds, const generics and code bloat.
Generics let one definition work for many types: fn largest<T: PartialOrd>(items: &[T]) -> &T, struct Stack<T>, enum Option<T>. Rust implements generics by monomorphization: at compile time, for each distinct set of type arguments that your program uses, the compiler generates a separate, fully specialized copy of the function or type. Vec<i32> and Vec<String> are two different types with their own compiled code.
The result is that generic code runs exactly as fast as hand-written, type-specific code. There is no boxing, no type tags and no virtual call unless you ask for one. The price is paid at build time and in binary size, not at run time.
fn pair<T: Clone>(x: &T) -> (T, T) { (x.clone(), x.clone()) } // pair(&1u8) and pair(&String::new()) compile to two separate functions
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
How monomorphization works
- The compiler type-checks the generic body once, using only the bounds you declared. If the body calls a method, the bound must provide it. This is why errors point at the definition rather than at use sites, unlike C++ templates.
- During code generation it collects every concrete instantiation the program needs (
largest::<i32>,largest::<f64>, ...) by following calls frommainand from all public items. - For each instantiation it substitutes the types and generates optimized code. Inlining and constant folding then work with full type knowledge, so
size_of::<T>()becomes a constant and aT::SYMBOLlookup becomes a literal. - Identical instantiations are shared. Whether two distinct types with identical machine code are merged is up to the linker and LLVM.
Usage notes
- Zero run-time cost for generics, but compile time and binary size grow with the number of instantiations. Large generic functions called with many types are a common reason for slow builds.
- Reduce bloat by moving type-independent code into a non-generic inner function: take
impl AsRef<str>, convert once, and call a function that takes&str. - Dynamic alternative:
dyn Traitcompiles one copy and calls through a vtable. See static versus dynamic dispatch. - Bounds go where they are needed. Put
T: Displayon the function orimplthat uses it, not on the struct definition, unless the struct itself needs it. whereclauses say the same as inline bounds but read better when long:where T: Clone + Debug, U: Into<String>.- Const generics (
[T; N],const N: usize) parameterize over values;Ncan be integers,boolandchar. - Turbofish:
Vec::<i32>::new(),"5".parse::<u8>(),iter.collect::<Vec<_>>()supply type arguments when inference needs help; see turbofish. - Unused type parameters need
PhantomData<T>to tell the compiler how the type relates toT. type_nameoutput is meant for diagnostics; its exact text is not guaranteed.