Generics
Generics may be used in:
- structs
- functions
- enums
- methods
Functions
Function example:
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = list[0];
for &item in list { if item > largest { largest = item; } } largest}
The function largest
is generic over some type T
.
We can call this function like this:
let number_list = vec![34, 50, 25, 100, 65];let result = largest(&number_list);
Structs
Struct example:
struct Point<T> { x: T, y: T,}
fn main() { let integer = Point { x: 5, y: 10 }; let float = Point { x: 1.0, y: 4.0 };}
Enums
Enum example:
enum Option<T> { Some(T), None,}
Methods
Method example:
struct Point<T> { x: T, y: T,}
// the T after impl means that we're defining this method generically// and T is not any specific typeimpl<T> Point<T> { fn x(&self) -> &T { &self.x }}
We can also specify a method for a concrete type T
:
impl Point<f32> { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() }}
Or, we could specify a method only for T
s that implement some traits:
impl<T: Display + PartialOrd> Point<T> { fn cmp_display(&self) { if self.x >= self.y { println!("The largest member is x = {}", self.x); } else P println!("The largest member is y = {}", self.y); }}