Skip to main content
Be Bitwise
RustTraits & Generics

Generic Types

Generics let one chunk of code serve multiple types without giving up type safety or runtime speed.

Generic Functions

rust
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

rust
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

rust
struct Pair<T, U> {
first: T,
second: U,
}
let p = Pair { first: 1, second: "hello" };
Key Concept

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:

asm
.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 .loop

The 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:

rust
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:

rust
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.0

Where Clauses

For complex bounds, use where:

rust
fn process<T, U>(t: T, u: U) -> String
where
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.

Try itUncomment blobs.show() and read the error, then implement std::fmt::Display for Opaque so it compiles.
Rust (1.40.0)