liveBook · Manning

Monomorphization

As explained in Learn Rust in a Month of Lunches

Monomorphization generates a separate concrete function or type implementation for each concrete type used with generic code.

Monomorphization turns a generic function into a separate concrete function for every type used with it. Rust performs this during compilation, so the resulting program can run faster. section 18.1.2

One generic function, two concrete forms

A generic `print_and_return<T>` called with a string and an `f64` can become forms such as `print_and_return_str(&str)` and `print_and_return_f64(f64)`. The compiler handles this automatically; you only notice that generic code may take slightly longer to compile. section 18.1.2

use std::fmt::Display;
 
fn print_and_return<T: Display>(input: T) -> T {
    println!("You gave me {input} and now I will give it back.");
    input
}
 
fn main() {
    let my_name = print_and_return("Windy");
    let small_number = print_and_return(9.0);
}

Inspect the generic function and its two calls that motivate the specialized forms. section 18.1.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines specialization and illustrates generated signatures, but stops short of compiler implementation details.
Examples
Uses `print_and_return` with a string and an `f64` to show two specialized function forms.
What it assumes
Assumes familiarity with generic functions and concrete argument types, while defining polymorphism and monomorphism in plain language.
What you can do after
Understand why generic Rust functions may cost compile time while avoiding runtime generic dispatch overhead.
How it connects
Connects generic functions with polymorphism, concrete types, compilation, and runtime performance.

Also explained in

Compare how 2 books explain monomorphization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.