[Solved] Converting from generic type as associated type to generic type

#1

Im trying to add the std::ops::Add trait to this point struct with two generic variables x and y that have to have the std::ops::Add trait and the std::fmt::Display trait but when i try adding these two variables in the Point’s std::ops::Add impl it gives an error saying it expects T but is getting T as std::ops::Add::Output

is it possible to convert between them or am i going about this all wrong?

this is my code.

struct Point<T: std::ops::Add + std::fmt::Display> {
x: T,
y: T,

}

impl<T: std::ops::Add + std::fmt::Display> std::ops::Add for Point {
type Output = Point;

fn add(self, other: Point<T>) -> Self::Output {
    Point {
        x: self.x + other.x,    // error occurs here
        y: self.y + other.y,    // and here
    }
}

}

#2

Add has an input Rhs type parameter that defaults to Self, but you still have to constrain the Output if you care what it is. This is useful to let T be a reference type that outputs a value. So you probably want T: Add<Output = T>, which is implicitly T: Add<T, Output = T>.

You could be completely generic and have your type Output = Point<<T as Add>::Output>, but that’s probably overkill.

#3

Ohh alright thanks very much man works perfectly!