Why should i assign return type twice

I can specify the type of returning value in the add function itself but why is it asking me to assign the type again?

impl ops::Add<Complex> for Complex {
    type Output = Complex;

    fn add(self, _rhs: Complex) -> Complex {
        Complex::default()
    }
}

Because the add trait is meant to be flexible.

  • impl ops::Add<Complex> is for the type to the right.
  • for Complex is for the type to the left.
  • type Output = Complex is for the return type but you changed the function signature in a way that obscured the relationship.
    You should instead use Self like this
impl Add<Self> for Complex {
    type Output = Self;
    fn add(self, _rhs: Self) -> Self::Output {
        Self::default()
    }
}
1 Like

This is to allow for one to also write

impl ops::Add<i32> for Complex {
    type Output = Complex;

    fn add(self, rhs: i32) -> Complex {
        self.real += rhs;
        self
    }
}

which means that you can do both complex + complex and complex + 42 or complex + num.

It lets you express that you can add a Duration to an Instant, but you can't add an Instant to a Duration (as the latter has no meaning).

3 Likes

is there any way to pass external_argument into trait implementations like how we do in C++ with templates?

impl Into<Index> for Complex {
    fn into(self) -> Index {
        self.real + external_argument
        todo!()
    }
}

Depends on what do you even mean by that phrase. Your Rust code doesn't make any sense, but perhaps you may write some C++ code that would make some sense?

That that question may be answered… because as it is I couldn't even imagine what you mean by your question: simple translation from trait to concept (closest thing to traits in C++) wouldn't be accepted by C++, too.

template <int N1, int N2>
struct Add {
    static const int value = N1 + N2;
};
const int compileTimeSum = Add<10, 20>::value

can i do something like this in rust?

You can do this, of course:

struct Add<const N1: i32, const N2: i32> {
}

impl<const N1: i32, const N2: i32> Add<N1, N2> {
    const value: i32 = N1 + N2;
}

const compileTimeSum: i32 = Add::<10, 20>::value;

But I strongly suspect that you would want some pretty much impossible in Rust with that (e.g. use that const to define a type).

1 Like

oh wait i confused you a little bit. but yes. that is kind of weird thinking from my side