Code Example Template
Deep-Dive System Documentation
Generics: Parametric Polymorphism
Generics allow functions, structs, and enums to operate on parametric types instead of single concrete types.
Basic Usage & Constraints
You can restrict generic parameters to types implementing specific traits using trait bounds (: TraitName):
use std::fmt::Debug;
fn log_action<T: Debug>(action: T) {
println!("System Event: {:?}", action);
}
log_action(100); // works because i32 implements Debug
log_action("HookTriggered"); // works because &str implements Debug
Compile-Time Monomorphization
How does Rust perform generics at runtime? It uses Monomorphization.
At compile time, the compiler looks at all concrete arguments used to invoke log_action. It duplicates the code, replacing T with the exact types used.
- Result: No dynamic casting, no interface lookup pointers.
- Performance: Direct static calls. Complete zero-overhead performance, matching hand-written separate functions.
Quick Reference Guide
struct Point<T> { x: T, y: T }