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 withi32andf64generatesfoo_i32andfoo_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_monomorphizemodule 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.
```