Using dyn with associated types


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/
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).


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.