Generics
Generic types with functions, structs, traits and lifetime.
Cheatsheet
#[derive(Debug)]
struct Point<T: Add> {
x: T,
y: T,
}
fn new_point<T>(x: T, y: T) -> Point<T>
where
T: Debug + Add,
{
todo!()
}
let p0 = new_point(1.0, 2.0);
let p1 = new_point::<u8>(1, 2);
impl<T> Pair<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
let a = Point::<u8>::new(1, 2);
Examples
- Generic types in Function
- Generic types in Struct and Enum
- Generic types in Method
fn largest<T>(list: &[T]) -> &T {}
struct Point<T, U> {
x: T,
y: U,
}
enum Option<T> {
Some(T),
None,
}
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
impl Point<f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
impl<T, U> Point<T, U> {
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
Point {
x: self.x,
y: other.y,
}
}
}
Questions
How to use type aliases with generics
The type alias helps in two ways: it makes code easier to write and it gives us a consistent interface across all of std::io.
type Result<T> = ::std::result::Result<T, MyError>;
type OptionI32 = Option<i32>;