[SOLVED] Why do I get: error[E0308]: mismatched types: note: expected type `()` found type `c::C`

Hello

Why do I get mismatched types?

    error[E0308]: mismatched types
  --> src/c.rs:18:16
   |
18 |         return C{a: a, b: b};
   |                ^^^^^^^^^^^^^ expected (), found struct `c::C`
   |
   = note: expected type `()`
              found type `c::C`

error: aborting due to previous error

The code contain files in the src folder.

Thanks

A.rs:

    pub struct A {
        a: i16
    }
    
    impl A {
        pub fn new() -> A {
            return A{a:0};
        }
        
        pub fn add(&self, i:i16) {
            self.a += i;
        }
        
        pub fn get(&self) -> i16 {
            return self.a;
        }
    }

B.rs:

    pub struct B {
        b: i16
    }
    
    impl B {
        pub fn new() -> B {
            return B{b:0};
        }
        
        pub fn add(&self, i:i16) {
            self.b += i;
        }
        
        pub fn get(&self) -> i16 {
            return self.b;
        }
    }
C.rs:
    use super::a::A;
    use super::b::B;
    
    pub struct C {
        a: A,
        b: B
    }
    
    impl C {
        pub fn new() {
            let a = A::new();
            let b = B::new();
            return C{a: a, b: b};
        }
        
        pub fn add(&self, i:i16) {
            self.a.add(i);
            self.b.add(i);
        }
        
        pub fn get(&self) -> i16 {
            return self.a.get() + self.b.get();
        }
    }

C::new doesn't have a return type notated.

Also, you don't need to use return. You can just end the line with the value you want to return without a semicolon.

impl C {
                 // note the return type added here at the end
    pub fn new() -> C {
        let a = A::new();
        let b = B::new();
        // note the omission of `return` as well as the omission of the semicolon
        C{a: a, b: b}
    }

This fairly common error could probably benefit from having a helpful note in the error message such as "add -> T to the function signature if you want to return a T".

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.