Monomorphization and code generation
Quick answer
Monomorphization specializes generic code for concrete type arguments needed by the program. It enables static dispatch but may increase compilation cost and binary size.
Static versus dynamic dispatch
rustc collects concrete instances for code generation. Generic bounds allow implementations to be selected for known types, while a trait object can call through a vtable. Optimizers can inline, merge or remove code; the source count of generic calls does not guarantee a corresponding count of emitted symbols. Queries and incremental compilation can reuse compiler work when dependencies allow it.
fn label<T: std::fmt::Display>(x: T) -> String { format!("[{x}]") }fn main() { println!("{} {}", label(7u32), label("ready")); }Expected stdout (not executed):
[7] [ready]The generic API is called with u32 and &str.
fn label(x: &dyn std::fmt::Display) -> String { format!("[{x}]") }fn main() { println!("{} {}", label(&7u32), label(&"ready")); }Expected stdout (not executed):
[7] [ready]Both calls use the same non-generic function signature; dynamic dispatch may be optimized.
Common mistake
Do not promise that generics are always faster or that trait objects always reduce binary size.
Try it yourself
Use rustc --emit=llvm-ir on each example and compare opt-level 0 and 3 without assuming exact symbol counts.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Monomorphization and code generation — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A generic function is used with several concrete types. Why inspect final artifacts before reporting symbol counts?
Monomorphization and code generation — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn label<T: std::fmt::Display>(x: T) -> String { format!("[{x}]") } fn main() { println!("{} {}", label(7u32), label("ready")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Monomorphization and code generation — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn label(x: &dyn std::fmt::Display) -> String { format!("[{x}]") } fn main() { println!("{} {}", label(&7u32), label(&"ready")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.