简体   繁体   中英

Reference associated type in trait bounds

I have a trait which is meant to tighten constraints on another trait, eg:

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM