Rust Generics
Generics
Look at these two functions. They do exactly the same thing, but one works with i32 numbers and the other with f64 numbers:
Example
fn bigger_i32(a: i32, b: i32) -> i32 {
if a > b { a } else { b }
}
fn bigger_f64(a: f64, b: f64) -> f64 {
if a > b { a } else { b }
}
fn main() {
println!("{}", bigger_i32(5, 10));
println!("{}", bigger_f64(2.5, 1.5));
}
Try it Yourself »
Writing the same code again for every type takes time, and it is easy to make mistakes. Generics let you write the code once, and use it with many types.
Generic Functions
A generic function has a type parameter in angle brackets < > after its name. The name T (short for "type") is a placeholder for a real type, like i32 or f64:
Example
fn bigger<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
fn main() {
println!("{}", bigger(5, 10));
println!("{}", bigger(2.5, 1.5));
println!("{}", bigger('a', 'z'));
}
Try it Yourself »
Rust replaces T with the right type each time you call the function: i32 for bigger(5, 10), f64 for bigger(2.5, 1.5) and char for bigger('a', 'z').
Trait Bounds
What does T: PartialOrd mean? It is a trait bound. It says that T can only be a type that implements the PartialOrd trait, which is the trait that lets values be compared with > and <. You learned about traits in the previous chapter.
Without the trait bound, Rust does not know if two T values can be compared, so the code does not compile:
Example
fn bigger<T>(a: T, b: T) -> T {
if a > b { a } else { b } // Error
}
Try it Yourself »
The error message even suggests the fix: add PartialOrd to T.
Generic Structs
Structs can be generic too. This Point struct can store whole numbers or decimal numbers:
Example
struct Point<T> {
x: T,
y: T,
}
fn main() {
let a = Point { x: 5, y: 10 };
let b = Point { x: 1.5, y: 4.25 };
println!("a = ({}, {})", a.x, a.y);
println!("b = ({}, {})", b.x, b.y);
}
Try it Yourself »
Note: x and y both use the type T, so they must have the same type. Point { x: 5, y: 4.25 } gives an error, because 5 is an integer and 4.25 is a float.
Generics You Have Already Used
Vec<T> is a generic struct: Vec<i32> is a vector of integers, and Vec<&str> is a vector of string slices.
Option<T> and Result<T, E> from the Option and Error Handling chapters are generic enums.
Why Use Generics?
- To write code once, and use it with many types
- To avoid copying the same function for each type
- To let the compiler check that the types are used correctly