Skip to content
ImagineWorld

Generics and Monomorphization

node_idnode-book_oop-to-rust_chapter-05-generics-and-monomorphization
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleGenerics and Monomorphization
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Generics and Monomorphization

Section titled “Chapter 5 — Generics and Monomorphization”

E pluribus unum. (Out of many, one.)

Traits define behavior contracts, but a function accepting only NewsArticle or only Tweet remains limited. The real power emerges when functions and types can work with any type meeting certain constraints. Generics provide this abstraction, allowing code to operate on types specified by callers rather than fixed at definition time. Combined with trait bounds, generics enable reusable code that remains type-safe and performs as if written specifically for each concrete type used.

Object-oriented developers are familiar with generics from Java, C#, and C++. Java’s List<String> and C#‘s Dictionary<K, V> use similar syntax. Yet the underlying mechanisms differ substantially. Java generics are erased at runtime; all type information disappears, and the JVM sees only raw types. C# preserves generic type information at runtime through reification. Rust takes a third path: monomorphization. The compiler generates specialized code for each concrete type, eliminating generics entirely from the final binary. This approach combines the flexibility of generic programming with the performance of hand-specialized code.

Generic types and functions

A generic function declares type parameters in angle brackets after the function name. These type parameters stand in for concrete types that callers provide. A function largest<T> might find the largest element in a slice of T values. The T is not a concrete type; it represents whatever type the caller uses. Calling largest on a slice of i32 produces an i32. Calling it on a slice of f64 produces an f64. The same function definition handles both cases.

The syntax places type parameters after the function name but before the parameter list:

fn largest<T>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}

This function does not compile. The comparison item > largest requires that T supports comparison, but an unconstrained generic type provides no guarantees about available operations. The compiler rejects the code because not every possible T can be compared with the greater-than operator.

Trait bounds constrain generic types to those implementing specific traits. Adding a bound requiring the PartialOrd trait allows comparison:

fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}

The bound T: PartialOrd means that T must implement PartialOrd, the trait defining comparison operations. Any type satisfying this bound can be used with the function. The compiler verifies the bound at each call site, ensuring type safety without runtime checks.

This differs from how Java generics work. In Java, generic methods can call methods on Object (or whatever bound is specified), but the actual method resolution happens at runtime through virtual dispatch. In Rust, the compiler knows the concrete type at each call site and generates direct calls to the concrete method implementations. The generic code becomes non-generic code during compilation.

The following comparison illustrates the fundamental difference between Java’s type erasure and Rust’s monomorphization:

// Java: type erasure at runtime
public class Container<T> {
private T value;
public T getValue() { return value; }
// Cannot do: new T() - type unknown at runtime
// Cannot do: value instanceof T - T erased
// At runtime, Container<String> and Container<Integer> are same class
}
// Both calls use identical bytecode
Container<String> strings = new Container<>();
Container<Integer> numbers = new Container<>();
// strings.getClass() == numbers.getClass() is true
// Rust: monomorphization at compile time
struct Container<T> {
value: T,
}
impl<T> Container<T> {
fn get_value(&self) -> &T { &self.value }
}
impl<T: Default> Container<T> {
fn new_default() -> Self {
Container { value: T::default() } // Works: T known at compile time
}
}
// Compiler generates separate code for each:
let strings: Container<String> = Container { value: String::new() };
let numbers: Container<i32> = Container { value: 0 };
// At runtime, Container<String> and Container<i32> are different types
// with different, specialized machine code

In Java, all generic type information disappears after compilation. A Container<String> and Container<Integer> are the same class at runtime, and code cannot create new instances of T or check if a value is an instance of T. In Rust, the compiler generates completely separate types and code for each concrete instantiation. Container<String> and Container<i32> are different types with different machine code, and trait bounds like T: Default can be used because the concrete type is known during compilation.

Generic structs and enums

Structs and enums can also be generic. A Point<T> struct might store x and y coordinates of type T, allowing points of integers, floats, or any other numeric type:

struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Point { x, y }
}
}

The impl block declares its own type parameter T, which corresponds to the T in the struct definition. Methods on generic types have access to the type parameter, and the Self type refers to the concrete instantiation (Point<i32> when T is i32, Point<f64> when T is f64).

Multiple type parameters allow different types within the same structure. A Point where x and y can have different types requires two parameters:

struct Point<T, U> {
x: T,
y: U,
}

This structure can hold a point with an integer x and a floating-point y, or any other combination. The flexibility comes at the cost of complexity; most designs use a single type parameter when the fields are conceptually the same kind of value.

Generic enums follow the same pattern. The standard library’s Option and Result types are generic enums:

enum Option<T> {
Some(T),
None,
}
enum Result<T, E> {
Ok(T),
Err(E),
}

Option has one type parameter for the contained value. Result has two: one for the success value and one for the error type. These definitions enable Option<i32>, Option<String>, Result<User, DatabaseError>, and countless other instantiations from a single definition.

Constraining impl blocks

Impl blocks can add additional bounds beyond what the type definition requires. A Point might have general methods available for any T, plus specialized methods available only when T meets certain requirements:

impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
impl<T: std::fmt::Display> Point<T> {
fn describe(&self) -> String {
format!("Point at ({}, {})", self.x, self.y)
}
}

The first impl block provides x() for any Point regardless of T. The second provides describe() only when T implements Display. Calling describe() on Point<i32> works because i32 implements Display. Calling it on a Point containing a type without Display produces a compile error.

This pattern enables progressive capability. A generic container might provide basic operations for all types, additional operations for types that support comparison, and further operations for types that support hashing. Each impl block adds capabilities conditional on the type parameter meeting its bounds.

Monomorphization: zero-cost abstraction

When the compiler encounters generic code, it does not produce generic machine code. Instead, it generates specialized versions for each concrete type used. A call to largest::<i32> produces a function specialized for i32, with direct comparisons between 32-bit integers. A call to largest::<String> produces a different function specialized for String, with calls to String’s comparison methods. The generic function exists only in source code; the compiled binary contains only concrete functions.

This process is called monomorphization, from “mono” (single) and “morph” (form). Each generic instantiation produces a single concrete form. The compiler creates as many specialized versions as needed and no more.

The following diagram illustrates monomorphization:

graph TD
    subgraph SRC["Source Code"]
        G["fn largest#lt;T: Ord#gt;(list: &[T]) -> &T"]
    end
    subgraph CS["Call Sites"]
        C1["largest(&integers)"]
        C2["largest(&strings)"]
        C3["largest(&floats)"]
    end
    subgraph BIN["Compiled Binary"]
        B1["largest_i32(list: &[i32]) -> &i32"]
        B2["largest_String(list: &[String]) -> &String"]
        B3["largest_f64(list: &[f64]) -> &f64"]
    end
    G --> C1 --> B1
    G --> C2 --> B2
    G --> C3 --> B3

[!visual-conversion] Monomorphization generates specialized code for each concrete type. Print diagram (PDF 166, printed p. 166) recreated in Mermaid; three stacked frames, labels verbatim.

The performance implications are significant. Generic code runs at the same speed as hand-written specialized code because, after compilation, it is hand-written specialized code. There is no runtime dispatch, no boxing of values, no type erasure. The generic abstraction costs nothing at runtime.

This stands in contrast to Java’s approach. Java generics exist only at compile time for type checking. At runtime, ArrayList<String> and ArrayList<Integer> are the same class operating on Object references. Values are boxed (primitives become wrapper objects), and casts are inserted where the code uses the generic type parameter. The JIT compiler can sometimes optimize away this overhead, but the possibility of runtime type errors (ClassCastException) remains, and the boxing overhead is often unavoidable.

C++ templates work more like Rust’s generics, generating specialized code for each instantiation. The key difference lies in error messages and compilation model. C++ template errors are notoriously difficult to understand because the compiler tries to instantiate the template and reports errors in terms of the instantiation. Rust’s trait bounds catch errors earlier: if a generic function requires T: Display and the body calls methods not in Display, the compiler rejects the function definition, not just problematic call sites. Errors appear where constraints are violated, not deep inside template instantiation.

The trade-off: binary size

Monomorphization increases binary size. Each specialization adds code to the final executable. A generic function used with ten different types produces ten copies of the function. For most applications, this trade-off favors generics: the performance benefits outweigh the space costs, and modern systems have abundant memory for code.

In constrained environments (embedded systems, WebAssembly modules where download size matters), the trade-off requires more consideration. Reducing the number of instantiations, using trait objects for dynamic dispatch, or reconsidering the design can help control binary size when needed.

Compile time also increases with heavy generic usage. Each instantiation must be compiled separately, and complex generic code with many bounds can slow the compiler. This is rarely a problem in practice, but extremely generic libraries sometimes optimize for compile time by limiting the generic surface area.

Trait objects vs generics: the Static/Dynamic trade-off

Generics with trait bounds provide static dispatch: the concrete type is known at compile time, and the compiler generates direct calls. Trait objects provide dynamic dispatch: the concrete type is unknown until runtime, and calls go through a vtable.

Both approaches have their place. Static dispatch offers better performance and enables more compiler optimizations. Dynamic dispatch offers flexibility: heterogeneous collections, returning different types from functions based on runtime conditions, and reduced binary size when many types share the same trait.

Consider a notification system that must send messages through various channels. The static approach uses generics:

fn send_notification<N: Notify>(notifier: &N, message: &str) {
notifier.send(message);
}
fn main() {
let email = EmailNotifier::new();
let sms = SmsNotifier::new();
send_notification(&email, "Hello via email");
send_notification(&sms, "Hello via SMS");
}

Each call to send_notification knows the concrete type at compile time. The compiler generates two versions of the function, one calling EmailNotifier’s send and one calling SmsNotifier’s send. No runtime dispatch occurs.

The dynamic approach uses trait objects:

fn send_notification(notifier: &dyn Notify, message: &str) {
notifier.send(message);
}
fn main() {
let email = EmailNotifier::new();
let sms = SmsNotifier::new();
send_notification(&email, "Hello via email");
send_notification(&sms, "Hello via SMS");
}

Now there is only one version of send_notification. It accepts any type implementing Notify through a trait object. At runtime, the call to send goes through the vtable to find the correct implementation.

The dynamic approach enables patterns that static dispatch cannot express. A Vec<Box<dyn Notify>> can hold a mix of EmailNotifier, SmsNotifier, and any other type implementing Notify. Iterating over this collection and calling send on each element dispatches to the correct implementation at runtime:

fn broadcast(notifiers: &[Box<dyn Notify>], message: &str) {
for notifier in notifiers {
notifier.send(message);
}
}

With generics alone, Vec<N> holds only one concrete type N. You cannot mix EmailNotifier and SmsNotifier in the same vector because they are different types. Trait objects erase the concrete type, leaving only the trait interface, which enables heterogeneous collections.

Choosing between static and dynamic dispatch

The choice depends on the specific requirements. Static dispatch (generics) is preferred when the concrete types are known at compile time, when performance is critical, or when the generic code benefits from additional compiler optimizations (inlining, specialization). Dynamic dispatch (trait objects) is preferred when concrete types are determined at runtime, when heterogeneous collections are needed, or when reducing binary size matters.

In my experience, most code benefits from starting with generics and moving to trait objects only when the need arises. Generics are the default abstraction mechanism in Rust, and the ecosystem is built around them. The standard library’s Iterator, From, Into, and many other traits are designed for generic use. Trait objects are the exception rather than the rule, reserved for cases where runtime flexibility is required.

The following diagram summarizes the trade-offs:

Dynamic Dispatch (Trait Objects)Static Dispatch (Generics)
Concrete type unknown until runtimeConcrete type known at compile time
Vtable lookup on each callDirect function calls
Limited optimization opportunitiesCompiler can inline and optimize
Single code path for all typesBinary size grows with instantiations

[!visual-conversion] Static dispatch optimizes for performance; dynamic dispatch optimizes for flexibility. Print chart (PDF 171, printed p. 171) of two labelled columns of four boxes each, recreated as a table; row pairing follows the boxes’ vertical positions, text verbatim.

Object safety revisited

Not all traits can be used as trait objects. A trait is object-safe if its methods can be called through a pointer without knowing the concrete type. Several conditions can make a trait not object-safe.

Methods returning Self prevent object safety because the concrete return type varies per implementation. A trait with fn clone(&self) -> Self cannot be made into a trait object because the vtable cannot represent the varying return types. The Clone trait handles this by being non-object-safe; heterogeneous collections of clonable objects require wrapper types or alternative designs.

Methods with generic type parameters prevent object safety because each instantiation would need a separate vtable entry. A trait with fn process<T>(&self, value: T) cannot be made into a trait object because the vtable would need infinite entries for all possible T.

Methods taking self by value can prevent object safety in some cases, though the rules are subtle. The general principle is that anything requiring knowledge of the concrete type’s size or layout at the call site prevents object safety.

When designing traits intended for use as trait objects, these constraints guide the API. Prefer methods taking &self or &mut self. Avoid returning Self. Avoid generic parameters on methods (generic parameters on the trait itself are fine, as long as they are specified when creating the trait object).

Associated types in depth

Associated types appeared briefly in the previous chapter. They are type placeholders defined within a trait that implementations fill in. The Iterator trait defines an associated type Item:

pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}

Implementations specify the concrete Item type:

pub struct Counter {
count: u32,
max: u32,
}
impl Counter {
pub fn new(max: u32) -> Self {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
// Using the iterator
fn main() {
let counter = Counter::new(5);
// All iterator adapter methods are available
let sum: u32 = counter
.filter(|n| n % 2 == 0)
.map(|n| n * n)
.sum();
println!("Sum of squares of even numbers: {}", sum);
}

The Counter iterator specifies Item = u32, meaning each call to next returns an Option<u32>. All the standard iterator adapters (filter, map, take, skip, collect, sum, etc.) work automatically because they are defined generically over any Iterator::Item.

Associated types differ from generic parameters on traits in a crucial way. A trait with a generic parameter can be implemented multiple times for the same type with different parameter values. A type could implement From<String> and From<i32> and From<Vec<u8>>, each implementation is independent.

A trait with an associated type can be implemented exactly once per type. A type implementing Iterator has exactly one Item type. This constraint simplifies usage: when calling methods on an Iterator, the Item type is unambiguous. With a hypothetical Iterator<T> trait, specifying which T is meant would require additional annotations.

The choice between generic parameters and associated types reflects whether multiple implementations make sense. Conversion traits (From, Into, TryFrom) use generic parameters because a type can reasonably convert from many sources. Iterator uses an associated type because each iterator produces one kind of element.

Associated types can have bounds. The trait definition might require that the associated type implement certain traits:

trait Container {
type Item: Clone + Debug;
fn get(&self, index: usize) -> Option<&Self::Item>;
}

Implementations must choose an Item type that satisfies the bounds:

use std::fmt::Debug;
trait Container {
type Item: Clone + Debug;
fn get(&self, index: usize) -> Option<&Self::Item>;
fn len(&self) -> usize;
fn is_empty(&self) -> bool { self.len() == 0 }
}
struct VecContainer<T> {
items: Vec<T>,
}
impl<T: Clone + Debug> Container for VecContainer<T> {
type Item = T;
fn get(&self, index: usize) -> Option<&Self::Item> {
self.items.get(index)
}
fn len(&self) -> usize {
self.items.len()
}
}
struct ArrayContainer<T, const N: usize> {
items: [T; N],
filled: usize,
}
impl<T: Clone + Debug + Default, const N: usize> Container for ArrayContainer<T, N> {
type Item = T;
fn get(&self, index: usize) -> Option<&Self::Item> {
if index < self.filled {
Some(&self.items[index])
} else {
None
}
}
fn len(&self) -> usize {
self.filled
}
}
// Generic function using Container trait
fn print_all<C: Container>(container: &C) {
for i in 0..container.len() {
if let Some(item) = container.get(i) {
println!("{:?}", item);
}
}
}

This propagates constraints through the type system: any code using a Container knows that the Item type implements Clone and Debug, enabling operations that require those capabilities.

Default associated types

Rust has an unstable feature, associated type defaults, that lets a trait supply a default for an associated type which implementations can override or accept. It is available only on the nightly compiler behind #![feature(associated_type_defaults)]:

trait Processor {
type Output = String;
fn process(&self) -> Self::Output;
}

With the feature enabled, an implementation can specify a different Output type or omit the specification to use String. On stable Rust, every implementation must name its Output type explicitly; when most implementations share one type, a common workaround is a type alias or a separate trait with a generic parameter that has a default.

Generic constraints in practice

Complex generic code often involves multiple type parameters with interrelated bounds. The where clause syntax helps manage this complexity:

fn process<T, U, V>(t: T, u: U) -> V
where
T: Iterator<Item = U>,
U: Clone + Into<V>,
V: Default,
{
// implementation
}

This function requires T to be an iterator producing U values, U to be cloneable and convertible into V, and V to have a default value. The where clause makes these relationships explicit and readable.

Bounds can also constrain associated types. A function might accept any iterator but require that its Item type implement a specific trait:

fn sum_debug<I>(iter: I)
where
I: Iterator,
I::Item: Debug + Add<Output = I::Item>,
{
// implementation
}

The bound I::Item: Debug + Add<Output = I::Item> specifies that the iterator’s item type must implement Debug and must support addition that returns the same type.

These constraints compose naturally. Generic code expresses exactly what it needs from type parameters, and the compiler verifies that callers provide types meeting those needs. The result is reusable code that remains type-safe without runtime overhead.

Chapter Highlights

Generic types and functions abstract over concrete types, enabling code reuse while maintaining type safety. Type parameters declared in angle brackets stand in for concrete types specified at each use site.

Trait bounds constrain generic types to those implementing specific traits, enabling the generic code to use trait methods.

Monomorphization transforms generic code into specialized code for each concrete type used. The compiler generates separate versions of generic functions and types, eliminating generics from the final binary. This process delivers zero-cost abstraction: generic code performs identically to hand-specialized code.

The trade-off is binary size and compile time. Each instantiation adds code to the binary. For most applications, the performance benefits justify this cost. In constrained environments, trait objects provide an alternative with a single code path at the cost of runtime dispatch.

Static dispatch through generics and dynamic dispatch through trait objects serve different needs. Generics excel when concrete types are known at compile time and performance matters. Trait objects excel when runtime flexibility is needed, such as heterogeneous collections or runtime-determined types.

Associated types define type placeholders that implementations fill in. Unlike generic parameters on traits, associated types allow exactly one implementation per type. They suit relationships where each implementing type has a natural, unique associated type.

Generic constraints compose through multiple bounds, where clauses, and bounds on associated types. Complex generic signatures express precise requirements, and the compiler verifies that callers meet those requirements.

The next chapter examines type conversions and operator overloading, exploring the traits that enable seamless transformations between types and the customization of operators for user-defined types.