Tsallaka zuwa abun ciki
Justice Tech School

Generics

Generics let code work with many types. Type parameters go in angle brackets and trait bounds limit them. The compiler creates specialised code (monomorphisation), so there is no runtime cost.

Example
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
    let mut m = items[0];
    for &i in items { if i > m { m = i; } }
    m
}
struct Pair<T> { a: T, b: T }
fn main() {
    println!("{} {}", largest(&[3, 9, 2]), largest(&[1.5, 0.5]));
    let p = Pair { a: 1, b: 2 };
    println!("{}", p.a + p.b);
}

Result

9 1.5
3

Exercise

Type parameter brackets.

struct PairT> { a: T }

Quiz Test

What does T: PartialOrd mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.