Generics (Rust)
Generics let you write functions, structs, and enums that work over many types using type parameters like <T>. Rust monomorphizes them at compile time, so generic code is as fast as hand-written specialized code.
Rust
A type parameter (conventionally T) is a placeholder filled in when the code is used. fn largest<T>(list: &[T]) -> &T works for any element type. Structs and enums are generic too — Vec<T>, Option<T>, and HashMap<K, V> are all in the standard library.
Generics are usually paired with trait bounds that say what the type must be able to do: <T: PartialOrd> means 'T can be compared'. Without bounds you can store and move a T but not call methods on it. The where clause keeps complex bounds readable.
Rust compiles generics by monomorphization — it generates a concrete copy for each type actually used. There is no boxing or runtime type lookup, so there is zero performance penalty compared to writing the type out by hand.
Syntax
fn largest<T: PartialOrd>(list: &[T]) -> &T { ... }
struct Pair<T> { a: T, b: T }Examples
Rust
fn max<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", max(3, 9));
println!("{}", max("apple", "pear"));
}Output:
9
pear