Skip to content
Tutorials Center
My learning

Topics

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.

Rust
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

Rust One definition, one copy per type

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.

Rust Trait bounds, associated constants and const generics

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.

Rust A bound that is not satisfied

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

  1. 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.
  2. During code generation it collects every concrete instantiation the program needs (largest::<i32>, largest::<f64>, ...) by following calls from main and from all public items.
  3. 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 a T::SYMBOL lookup becomes a literal.
  4. 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 Trait compiles one copy and calls through a vtable. See static versus dynamic dispatch.
  • Bounds go where they are needed. Put T: Display on the function or impl that uses it, not on the struct definition, unless the struct itself needs it.
  • where clauses 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; N can be integers, bool and char.
  • 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 to T.
  • type_name output is meant for diagnostics; its exact text is not guaranteed.