Generics
A generic item is parameterised by types (and sometimes lifetimes and constants). The compiler monomorphises it: one compiled copy per concrete set of parameters.
Detailed Explanation
fn first<T>(items: &[T]) -> Option<&T> works for any T. You do not write first_i32 and first_string. The compiler writes them for you when you call first with a [i32] and a [String]. That process is monomorphisation. It is why generic Rust is fast — each copy is specialised — and why generic Rust can compile slowly — each copy is compiled.
Type parameters are written in < > on functions, structs, enums, impls, and traits. struct Pair<T> { a: T, b: T } is a pair of the same type. struct Pair<T, U> { a: T, b: U } is a pair of two types. Parameters may carry bounds: T: Clone. Without a bound, the body can only move, borrow, and drop T.
Lifetimes are generic parameters too: fn longest<'a>(a: &'a str, b: &'a str) -> &'a str. Const generics are the third kind: struct Block<const N: usize>([u8; N]). Block<4> and Block<8> are different types. Const generics replace a family of macros that used to generate Block1, Block2, Block4.
A generic struct is not one type. Pair<i32> and Pair<String> have different layouts, different drop glue, and different monomorphised methods. You cannot put both in a Vec without wrapping them in an enum or a trait object.
Turbofish is the syntax that names the parameters at the call site: collect::<Vec<_>>() or parse::<u16>(). Use it when inference does not have enough context. Prefer letting inference work; turbofish is the escape hatch, not the default style.
What it costs: binary size and compile time grow with the number of unique parameter combinations. A tiny generic helper used with fifty types is fifty functions. A large generic algorithm used with two types is two copies and is usually the right deal. dyn Trait is the way to pay once at runtime instead.
When you write a generic: the algorithm is the same for many types. When you write a concrete type: there is only one type that makes sense, or the generic bounds have become a page of constraints.
Code Examples
fn first<T>(items: &[T]) -> Option<&T> {
items.get(0)
}
struct Pair<T> {
a: T,
b: T,
}
fn main() {
println!("{:?}", first(&[10, 20])); // prints: Some(10)
let pair = Pair { a: "ada", b: "grace" };
println!("{} {}", pair.a, pair.b); // prints: ada grace
let n = "42".parse::<u16>().unwrap(); // turbofish names the type
println!("{n}"); // prints: 42
}Common Gotchas
A generic body cannot use methods it has no bound for
`item.clone()` requires `T: Clone`. The error points at the call; the fix is the bound, not an unwrap.
Monomorphisation multiplies code
A 200-line generic used with twenty types is roughly four thousand lines in the binary. Keep heavy generics few, or hide them behind `dyn`.
`Pair<i32>` is not `Pair<u32>`
There is no implicit conversion between instantiations. Map the fields or write a `From` impl.