What Is Monomorphization and How Does It Affect Binary Size?

Monomorphization creates specialized code copies for each generic type usage, ensuring performance but increasing binary size.

Monomorphization is the process where the Rust compiler generates a separate, specialized version of a generic function or struct for every concrete type used in the code, which increases binary size because each type combination results in duplicated machine code.

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

fn main() {
    let ints = vec![1, 2, 3];
    let chars = vec!['a', 'b', 'c'];
    // Compiler generates: largest_i32 and largest_char
    let _ = largest(&ints);
    let _ = largest(&chars);
}

The compiler creates distinct implementations like largest_i32 and largest_char at compile time, meaning if you use a generic with ten different types, the final binary contains ten copies of that function's logic.