🦀 Rust Advanced

What are zero-cost abstractions and monomorphization in Rust?

Answer

Zero-cost abstractions is Rust's guarantee that high-level constructs (iterators, generics, trait implementations, async/await) compile down to code as efficient as hand-written low-level code — you don't pay a runtime cost for the abstraction layer. The mechanism behind this for generics is monomorphization: when the compiler encounters a generic function like fn max<T: Ord>(a: T, b: T) -> T, it generates a separate, fully concrete copy of the function for each unique type it is called with (max_i32, max_f64, etc.) at compile time. Each monomorphized copy can be fully optimized and inlined by LLVM. The trade-off is longer compile times and larger binary sizes compared to dynamic dispatch, but zero runtime overhead. Iterator chains are a canonical example: they compile to tight loops with no heap allocation or function call overhead.