Ardakaniz
Ardakaniz

Reputation: 165

Type annotation required even when provided

I want to do something like this:

trait Trait {
    type Type;

    fn function<T>(val1: &T, ty: T::Type)
        where T: Trait
    {}
}

struct Struct;
impl Trait for Struct {
    type Type = u32;
}

fn main() {
    let val = Struct;
    Trait::function(&val, 5u32);
}

And I got the error: error[E0284]: type annotations required: cannot resolve `<_ as Trait>::Type == _` (c.f rust playground)

But even when I add type annotation (Trait::function::<Struct>(&val, 5u32)), I have the same error.

Any clue about the reason of this error?

Upvotes: 0

Views: 69

Answers (1)

Peter Hall
Peter Hall

Reputation: 58715

The trait doesn't mention self or Self, but it seems like you are expecting it to somehow infer which instance you intended.

Suppose you had another implementation of Trait:

struct Struct2;
impl Trait for Struct2 {
    type Type = u32;
}

Then, even though you are passing a Struct reference as the first argument, it would make sense for either implementation. This is ok:

let val = Struct;
<Struct as Trait>::function(&val, 5u32);

And this is ok:

let val = Struct;
<Struct2 as Trait>::function(&val, 5u32);

If you intended for the type passed to function to determine the instance, then the argument should be typed as Self instead of T:

trait Trait {
    type Type;

    fn function(&self, ty: Self::Type) {}
}

Now, it will correctly infer the instance without additional type annotations.

Upvotes: 2

Related Questions