The method return value of trait

struct Container(i32, i32);

trait Contains{
    type A;
    type B;
    fn contains(&self, _: &Self::A, _: &Self::B) -> bool;
    fn first(&self) -> Self::A;
    fn last(&self) -> Self::B;
}

impl Contains for Container{
    type A = i32;
    type B = i32;
    fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool{
        (&self.0 == number_1) && (&self.1 == number_2)
    }
    
    fn first(&self) -> Self::A{self.0}
    fn last(&self) -> Self::B{self.1}
}


fn difference<C: Contains>(container: &C) -> i32 {
    container.last() - container.first()
}

fn main() {
    let number_1 = 3;
    let number_2 = 10;

    let container = Container(number_1, number_2);

    println!("Does container contain {} and {}: {}",
        &number_1, &number_2,
        container.contains(&number_1, &number_2));
    println!("The difference is: {}", difference(&container));
}

in the impl Contanis for container', I had set up the 'type A = i32' and 'type B = i32'. and the method of first and last's return value type is Self::A or Self::B. but here is error that

|     container.last() - container.first()
   |     ---------------- ^ ----------------- <C as Contains>::A
   |     |
   |     <C as Contains>::B

so compiler can't return the specific value of Self::A and Self::B.

Your difference method should either take a &Container, change the bound to C: Contains<A=i32, B=i32> or add the C::B: Sub<C::A, Output = i32> bound. Right now nothing prevents another type from implementing Contains with an A and B different from i32

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