Generic Types
Generics let one chunk of code serve multiple types without giving up type safety or runtime speed.
Generic Functions
fn largest<T: PartialOrd>(list: &[T]) -> &T { let mut largest = &list[0]; for item in &list[1..] { if item > largest { largest = item; } } largest}
let numbers = vec![34, 50, 25, 100, 65];println!("Largest: {}", largest(&numbers));
let chars = vec!['y', 'm', 'a', 'q'];println!("Largest: {}", largest(&chars));Generic Structs
struct Point<T> { x: T, y: T,}
impl<T> Point<T> { fn new(x: T, y: T) -> Self { Point { x, y } }}
let integer_point = Point::new(5, 10);let float_point = Point::new(1.0, 4.0);Multiple Type Parameters
struct Pair<T, U> { first: T, second: U,}
let p = Pair { first: 1, second: "hello" };Rust monomorphizes generics at compile time. Every concrete type used spawns its own copy of the function. largest::<i32> and largest::<char> end up as two separate functions in the binary. Runtime cost: nothing. The generated code is as quick as if you'd hand-written the type-specific version yourself.
You can see the two copies for yourself. Compile largest plus one caller for each type for x86-64 (rustc -C opt-level=z --emit asm) and the object file holds two symbols, which demangle to largest::<char> and largest::<i32>. Here's the loop from the i32 copy, with the labels renamed:
.loop: test rcx, rcx ; any elements left? je .done mov esi, dword ptr [rax] ; load item mov rdx, rax cmp esi, dword ptr [rdi] ; item > largest? jg .keep ; i32: signed compare mov rdx, rdi.keep: add rax, 4 add rcx, -4 mov rdi, rdx jmp .loopThe char copy is byte-for-byte the same shape with one change: jg becomes ja. A char is an unsigned 32-bit scalar value and an i32 isn't, so PartialOrd compiles to an unsigned compare in one copy and a signed compare in the other. No type information survives to run time. Each copy just has the right instruction baked in.
Generic Enums
You've already been using generic enums:
enum Option<T> { Some(T), None,}
enum Result<T, E> { Ok(T), Err(E),}Type-Specific Methods
You can scope methods to a specific generic instantiation:
impl Point<f64> { fn distance_from_origin(&self) -> f64 { (self.x.powi(2) + self.y.powi(2)).sqrt() }}
// This method only exists for Point<f64>, not Point<i32>let p = Point::new(3.0, 4.0);println!("Distance: {}", p.distance_from_origin()); // 5.0Where Clauses
For complex bounds, use where:
fn process<T, U>(t: T, u: U) -> Stringwhere T: Display + Clone, U: Debug + PartialOrd,{ format!("{} - {:?}", t, u)}Equivalent to inlining the bounds, but a lot kinder on the eyes once the constraint list grows.
Build one yourself. Stack<T> works for any T, but show() lives in an impl<T: Display> block, so it only exists for stacks of printable things.