trait-concept

Rust Monomorphization of generic code

Rust commonly generates type-specific code for generic instantiations. Different concrete types may increase generated code and compilation work, although optimization can inline, share or remove code. Source-level instantiation is not a guarantee of separate machine-code symbols. Expected output (not executed): 6 14 Why: The two calls use different concrete types and their addition implementations. Common mistake: Inferring binary size or timing from the number of generic calls alone.

Formal Syntax & Structure

rust syntaxrust
fn f<T: Trait>(value: T)

Working Example

Example Snippetrust
fn twice<T: std::ops::Add<Output = T> + Copy>(value: T) -> T { value + value }fn main() { println!("{} {}", twice(3_u16), twice(7_u64)); }
Rust Reference