[英]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
: 如果我使用的是泛型而不是关联的类型,那么我可以告诉Rust
MyAssoc
在特征A
和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. 您可以通过
Self
引用实现类型,因为B: A
, Self::MyAssoc
已经存在。
trait B: A where Self::MyAssoc : AssocB {}
This prohibits impl B for T {}
when <T as A>::MyAssoc
does not implement AssocB
. 当
<T as A>::MyAssoc
没有实现AssocB
时,这将禁止impl B for T {}
使用AssocB
。 (example) (例)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.