How to impl a trait for another generic trait?

I know how to impl a trait for another concrete trait, but how does one impl a trait for all instantiations of a generic trait? I have:

trait Foo<T> {...}

trait Bar {...}

impl<T> Bar for ???

At issue is the rule requiring generic parameters to be used in certain ways, and this disallows:

impl <T, F> Bar for F where F: Foo<T> ...

The only thing that looks like it might work and is syntactically correct is:

impl <T> Bar for dyn Foo<T> ...

but this doesn't seem to work as I expected. I'm not sure what it does at all.

That's the rule I am referring to, but none of the work-around examples in that link apply in this case, as far as I can tell.

More details: I need Bar methods that are impl'ed by Foo<T> callable on a &dyn Bar reference that started as a &dyn Foo<T> reference.

If you are dealing with &dyn references anyways the impl <T> Bar for dyn Foo<T> should work.

1 Like

There might be some OO related confusion. Types that implement a trait aren't really "instantiations" of the trait; implementing a trait doesn't mean the implementor is a subtype of that that trait; traits aren't types.

dyn Foo<T> is a type -- a type distinct from any implementor -- and you're implementing the Bar trait for that type. You might want or need:

//                          vvvv
impl <T> Bar for dyn Foo<T> + '_ { ... }

Without that, you're implementing for dyn Foo<T> + 'static.

But from what you've posted so far, I'm not sure if it will help or not.

How are you getting from &dyn Foo<T> to &dyn Bar? Have any (reduced) code you can share?

I'm rethinking what I thought was a need to start with &dyn Foo<T>. I think that on the side of the interface that knows T, I will have a reference to something that is impl Foo<T>, and will have to go from that to &dyn Bar on the other side of the interface.

In fact, I think I could always wrap the impl Foo<T> in a repr transparent struct so that I can (unsafe, but safe because of the transparent repr) cast from a &impl Foo<T> to a reference to that wrapper struct. Then I can impl Bar for the wrapper struct.

The 20K foot view of what I'm trying to accomplish is: I am not yet using Rust dynamic libs, but I know I will eventually want to. I want to prepare by constructing an interface that passes &dyn Trait and primitive types only. However, one side of the interface wants to use a generic trait that is ultimately parameterized by types known to that same side of the interface (Foo and T in Foo<T> in my example), while the other side of the interface wants a concrete trait (Bar) connected to that. In some cases (different Foos and Bars in each case), I will need the concrete trait to impl the generic one, and in other cases, vice versa. Obviously, all impls are on the side that knows T.