Invalid types when returning the result of adding two generics

I study Rust, read the Rust homepage, and tried small sample programs. Here is the code that fails:

use std::ops::Add;

pub struct Complex<T> {
    pub re: T,
    pub im: T,
}

impl <T: Add> Add<Complex<T>> for Complex<T> {
    type Output = Complex<T>;
    fn add(self, other: Complex<T>) -> Complex<T> {
        Complex {re: self.re + other.re, im: self.im + other.im}
    }
}

Here is the error message:

src/lib.rs:11:3: 11:59 error: mismatched types:
 expected `Complex<T>`,
    found `Complex<<T as core::ops::Add>::Output>`
(expected type parameter,
    found associated type) [E0308]
src/lib.rs:11       Complex {re: self.re + other.re, im: self.im + other.im}
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I do not understand why it does not compile.

+4
source share
3 answers

Addtrait is defined as

pub trait Add<RHS = Self> {
    type Output;
    fn add(self, rhs: RHS) -> Self::Output;
}

That is, for a given type Self(type for which implemented a sign), and the type of right-hand side ( RHSthat is added thing), will have a unique style that is created Output.

Conceptually, this allows you to create a type Athat can have a type Badded to it, which will always generate a third type C.

T Add. , RHS , , (RHS = Self). , .

:

  • , Complex, T:

    impl<T> Add<Complex<T>> for Complex<T> 
        where T: Add
    {
        type Output = Complex<T::Output>;
    
        fn add(self, other: Complex<T>) -> Complex<T::Output> {
            Complex {re: self.re + other.re, im: self.im + other.im}
        }
    }
    
  • T , :

    impl<T> Add<Complex<T>> for Complex<T> 
        where T: Add<Output = T>
    {
        type Output = Complex<T>;
    
        fn add(self, other: Complex<T>) -> Complex<T> {
            Complex {re: self.re + other.re, im: self.im + other.im}
        }
    }
    
+5

add Complex<<T as core::ops::Add>::Output>. <T as core::ops::Add>::Output (.. Output Add<T> T) , T. Output, , :

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

    fn add(self, other: Complex<T>) -> Complex<T> {
        Complex { re: self.re + other.re, im: self.im + other.im }
    }
}

, Complex<T> Complex<U> , T a U, a Complex<<T as Add<U>>::Output>.

impl<T: Add<U>, U> Add<Complex<U>> for Complex<T> {
    type Output = Complex<<T as Add<U>>::Output>;

    fn add(self, other: Complex<U>) -> Self::Output {
        Complex { re: self.re + other.re, im: self.im + other.im }
    }
}
+4

You need to specify the type of output Addfor T:

impl <T: Add<Output = T>> Add for Complex<T> {
    type Output = Complex<T>;
    fn add(self, other: Complex<T>) -> Complex<T> {
        Complex {re: self.re + other.re, im: self.im + other.im}
    }
}
0
source

All Articles