Monomorphization in Rust

Process in Rust compiler (rustc) that converts generic code (e.g., using <T>) into type-specific (monomorphic) code at compile time.

  • Purpose: Ensures type-safe, optimized machine code with no runtime overhead for generics.
  • How It Works:
    • Generic functions/types are replaced with concrete versions for each used type.
    • Example: fn foo<T>(x: T) called with i32 and f64 generates foo_i32 and foo_f64.
  • Pros:
    • Fast execution (no runtime type resolution).
    • Type safety guaranteed at compile time.
  • Cons:
    • Increases compile time.
    • Larger binary size if many types are used.
  • Context: Handled by rustc_monomorphize module in Rust compiler.
  • Example:
    fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T { a + b }
    // Compiler generates add_i32, add_f64, etc., for each type used.
    ```