Calling a generic trait function

Hi all,

I can't understand why in the following example, func3 is not compiling. I can understand why func2 doesn't but because of the trait bound on AB, func3 should.

struct S(u8);

trait Lookup<T> {
    fn foo(&self);
}

struct A;
struct B;

trait AB{}
impl AB for A{}
impl AB for B{}

impl Lookup<A> for S {
    fn foo(&self) {
        println!("foo A");
    }
}

impl Lookup<B> for S {
    fn foo(&self) {
        println!("foo B");
    }
}

impl S {
    fn func1(&self, condition: bool) {
        if condition {
            Lookup::<A>::foo(self);
        } else {
            Lookup::<B>::foo(self);
        }
    }
    
    fn func2<T>(&self, condition: bool) {
        if condition {
            Lookup::<T>::foo(self);
        } else {
            Lookup::<T>::foo(self);
        }
    }    
    
    fn func3<T: AB>(&self, condition: bool) {
        if condition {
            Lookup::<T>::foo(self);
        } else {
            Lookup::<T>::foo(self);
        }
    }
}

Any explanation welcome !

Thanks in advance.

struct C;

impl AB for C {}

S(0).func3::<C>(true); // this has to compile because `C: AB`

Maybe you meant something like this?

    fn func4<T>(&self, condition: bool)
    where
        Self: Lookup<T>
    {
        if condition {
            Lookup::<T>::foo(self);
        } else {
            Lookup::<T>::foo(self);
        }
    }
1 Like

@trentj Thanks a lot !!

What I missed when the trait bound with Self. Now it works as expected:

fn main() {
    let s = S(0);
    s.func4::<A>(true); // prints "foo A"
    s.func4::<B>(true);    // prints "foo B"
} 

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.