user
user

Reputation: 5390

Reference associated type in trait bounds

I have a trait which is meant to tighten constraints on another trait, e.g.:

trait AssocA {}
trait AssocB: AssocA {}
trait A { type MyAssoc: AssocA; }
trait B: A { type MyAssoc: AssocB; }

If I were using generics rather than associated types, I'd be able to tell Rust that MyAssoc is the same across traits A and B:

trait AssocA {}
trait AssocB: AssocA {}
trait A<MyAssoc> where MyAssoc: AssocA {}
trait B<MyAssoc>: A<MyAssoc> where MyAssoc: AssocB { }

How can I do the same with associated types?

Upvotes: 0

Views: 477

Answers (1)

user395760
user395760

Reputation:

You can refer to the implementing type via Self and since B: A, Self::MyAssoc already exists.

trait B: A where Self::MyAssoc : AssocB {}

This prohibits impl B for T {} when <T as A>::MyAssoc does not implement AssocB. (example)

Upvotes: 1

Related Questions