Using dyn with associated types

Hi,

I am wondering why this little code doesn't compile:

trait Foo {
}

trait Bar {
    type T : Foo;
    
    fn func(&self, _: &dyn Self::T);
}

Claiming that type T is not found in Self:

error[E0405]: cannot find trait `T` in `Self`
  --> src/lib.rs:25:34
   |
25 |     fn func(&self, _: &dyn Self::T);
   |                                  ^ not found in `Self`

While if I remove the dyn keyword it compiles with no errors.

Thank you

T is a type, not a trait. type T: Foo means "implementors will provide a type that implements Foo.

The type an implementor provides might by dyn Foo, but that's not up to the trait. If the trait needs to specify that type in particular, then it isn't variable, and doesn't need to be an associated type. You can just write fn func(&self, _: &dyn Foo).

2 Likes

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.