I have the following example (which doesn't compile):
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U>
where
T : Copy,
U : Copy,
{
fn new(x: T, y: U) -> Self {
Self { x, y }
}
fn x(self: &Self) -> T {
self.x
}
fn y(self: &Self) -> U {
self.y
}
}
trait Distance<T> {
fn distance<V, W>(self: &Self, other: &Point<V, W>) -> T
where
V: Copy,
W: Copy;
}
impl<T, U> Distance<f64> for Point<T, U>
where
T: Copy + Into<f64>,
U: Copy + Into<f64>,
{
fn distance<V, W>(self: &Self, other: &Point<V, W>) -> f64
where
V: Copy + Into<f64>,
W: Copy + Into<f64>,
{
// Cast fields to f64 and do all the calculations as f64
}
}
impl<T, U> Distance<i32> for Point<T, U>
where
T: Copy + Into<i32>,
U: Copy + Into<i32>,
{
fn distance<V, W>(self: &Self, other: &Point<V, W>) -> i32
where
V: Copy + Into<i32>,
W: Copy + Into<i32>,
{
// Cast fields to i32 and do all the calculations as i32
}
}
How can I further constrain the function distance
implementation so that V and W are Into, while on the trait definition they remain only Copy, so in the call site I could do:
let p1 = Point::new(10, 10);
let p2 = Point::new(20, 20);
let integral_distance = Distance::<i32>::distance(&p1, &p2);
let float_distance = Distance::<f64>::distance(&p1, &p2);
It seems odd that I can constrain Point<T, U> further while using a trait but I can't constrain further the function of a trait on its implementation, after all, it is more strict on its' implementation than on its' definition. Or maybe I am missing something? ( I am just learning Rust and I come from a C++ background).