Why do I have to do `<MyStruct as Trait>::static_function` instead of `Trait::static_function`

In the following code I have to do <AA as A>:: but I actually wanted to do A::

trait A{
    fn is_true(&self) -> bool;
    fn both_true<T: A, U: A>(t: &T, u: &U) -> bool{
        t.is_true() && u.is_true()
    }
}

struct AA{
    value: bool
}

impl A for AA{
    fn is_true(&self) -> bool {
        self.value
    }
}

fn main() {
    let aa1 = AA{value: true};
    let aa2 = AA{value: false};
    //I wanted to do this:
    //A::both_true(&aa1, &aa2);
    <AA as A>::both_true(&aa1, &aa2);
}

I don't see why I need AA as A since both_true only has knowledge of types that implement A
.

Because it's ambiguous. Perhaps you want this instead:

trait A {
    fn is_true(&self) -> bool;
    fn both_true(t: &Self, u: &Self) -> bool{
        t.is_true() && u.is_true()
    }
}

But there could be implementations of A for multiple types, and there's no way to pick it backes on the arguments, since those are also generic.

Perhaps what you actually wanted is for both_true to just be a normal generic function, not part of the trait?

Since the method don't uses self at all the compiler don't know with implementation of A to use since there could be a other implementation like

struct BB;

impl A for BB {
    fn is_true(&self) -> bool {
        false
    }
    fn both_true<T: A, U: A>(t: &T, u: &U) -> bool{
        false
    }
}

an if i write A::both_true(...) the compiler has no idea what implementation to use the one from AA or the one from BB. The method signature even allow you to do <BB as A>::both_true(&aa1, &aa2).

You more likely want to have both_true() as a free standing function with the same signature as you have now or you change the signature of the method to some think like

trait A{
    fn is_true(&self) -> bool;
    fn both_true<U: A>(&self , u: &U) -> bool{
        self.is_true() && u.is_true()
    }
}
1 Like

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.