rust-book/generics/src/point.rs

35 lines
756 B
Rust

// Double generic types for a struct
pub struct DoubleGenericPoint<T, U> {
pub x: T,
pub y: U,
}
impl<T,U> DoubleGenericPoint<T, U> {
// Takes a generic of potentially different types than the parent struct
pub fn mixup<V, W>(self, other: DoubleGenericPoint<V,W>) -> DoubleGenericPoint<T, W> {
DoubleGenericPoint {
x: self.x,
y: other.y
}
}
}
pub struct Point<T> {
pub x: T,
pub y: T,
}
// Implement generic methods on a generic struct
impl<T> Point<T> {
pub fn x(&self) -> &T {
&self.x
}
}
// Implement a method for only a specific type of generic
impl Point<f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}