One copy per type
At the start of the theme, one cookie cutter stamped a star out of any dough, and one function largest picked the larger of numbers, letters and fractions. But a processor has no instruction for "compare anything". It compares integers with one instruction and floating-point numbers with another. So how does one function work with both?
The answer: in the finished program there is no single function. This is where the cookie cutter picture stops being accurate. One cutter stamps any dough, while the compiler, before the program runs, casts a separate cutter for each dough you used.
Monomorphization is turning one generic function into several ordinary ones: one copy for each type it was called with. In each copy, a concrete type stands in place of T. Step through the program and watch the name of the frame that appears at each call: with each new type, a different copy runs.
1fn largest<T: PartialOrd>(a: T, b: T) -> T {2 if a > b { a } else { b }3}4 5fn main() {6 let n = largest(7, 3);7 println!("{n}");8 let x = largest(1.5, 2.5);9 println!("{x}");10 let c = largest('a', 'z');11 println!("{c}");12}
The arguments are two i32 values, so the copy largest::<i32> runs, with T replaced by i32.
Let's sum up the trace:
- The compiler found three calls to
largest: withi32, withf64and withchar. - For each type it wrote a copy of its own:
largest::<i32>,largest::<f64>andlargest::<char>. - Each call in
maingoes straight to its copy, and at run time there is nothing left to choose.
Copies appear only for the types the function was actually called with. The program has no call with u8, so it has no copy largest::<u8> either.
A copy's name
The form largest::<i32> works in code too: ::<…> after a function's name picks T explicitly. Usually the compiler infers the type, but you can name it yourself:
fn largest<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", largest::<i32>(7, 3)); // 7
println!("{}", largest::<f64>(1.5, 2.5)); // 2.5
println!("{}", largest::<char>('a', 'z')); // z
}"42".parse::<i32>() uses the same form: parse is a generic function too, and ::<i32> picks its T. There you have to name the type, because it cannot be inferred from the arguments.
The price of copies
While the program runs, nothing. Each copy is an ordinary function with a known type: no type checks at run time, no choosing a copy. A generic function runs as fast as the functions largest_i32 and largest_char written by hand. This is called a zero-cost abstraction: the convenience of generics costs nothing at run time.
You pay at build time:
- the compiler writes and checks every copy, so the build takes longer;
- every copy takes up space, so the finished program grows with each new type.
This is a classic interview question: "How do generics work in Rust, and how do they differ from Java's?" The answer:
- Rust makes a copy of a generic function for each type, which is monomorphization;
- Java erases the types: one version of the code remains, and it works with every type through
Object; - Rust's copies cost nothing at run time, but they lengthen the build and enlarge the program.
Common mistake
One call is given values of two different types:
fn largest<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", largest(7, 2.5)); // ✗
}error[E0308]: mismatched typesThe program does not compile. One call means one copy, and in a copy T is one type: 7 is an integer, and 2.5 is a floating-point number. There is no copy "for an integer and a float at once". The fix is to pass values of one type: largest(7.0, 2.5).
Key points
- The compiler makes a copy of a generic function for each type:
largest::<i32>,largest::<f64>. - Copies are created before the program runs, and only for the types the function was called with.
- At run time copies cost nothing; you pay for them in build time and program size.
- In one call
Tis one type, solargest(7, 2.5)is error E0308.