在Rust中引入通用关联类型之前,已经有人询问过这个问题,尽管它们已被提出并得到开发。
我的理解是trait泛型和关联类型之间在可以绑定到一个结构体上的类型数量上存在差异。
泛型可以绑定任意数量的类型:
struct Struct;
trait Generic<G> {
fn generic(&self, generic: G);
}
impl<G> Generic<G> for Struct {
fn generic(&self, _: G) {}
}
fn main() {
Struct.generic(1);
Struct.generic("a");
}
关联类型 与1个类型绑定:
struct Struct;
trait Associated {
type Associated;
fn associated(&self, associated: Self::Associated);
}
impl Associated for Struct {
type Associated = u32;
fn associated(&self, _: Self::Associated) {}
}
fn main() {
Struct.associated(1);
// Struct.associated("a"); // `expected u32, found reference`
}
通用关联类型是这两者的混合体。它们绑定到一个类型,恰好有1个关联生成器,而这个关联生成器反过来可以关联任意数量的类型。那么这种通用关联类型与前面示例中的通用
有什么区别呢?struct Struct;
trait GenericAssociated {
type GenericAssociated;
fn associated(&self, associated: Self::GenericAssociated);
}
impl<G> GenericAssociated for Struct {
type GenericAssociated = G;
fn associated(&self, _: Self::GenericAssociated) {}
}
fn count<I: for<'a> Iterator<'a>>(it: I)
— 你能否举个例子说明它如何因为过于限制(即秘密的'static
约束)而失败? - vikram2784WindowMut
迭代器传递给count
,因为T
不是“静态的”。 - Lukas Kalbertodtfor<'s> T: 's
which is equivalent toT:'static
”⸺这是因为迭代器间接地借用了T
(即通过切片本身借用具有生命周期'a
的元素)吗? - vikram2784for<'s> B
的意思是“对于所有可能的生命周期,约束B必须成立”。这个语句也包括“B必须在'static
生命周期中成立”,对吗?因为那是“一个可能的生命周期”。而且由于'static
在某种程度上“包含”所有其他生命周期,所以这两个约束是等价的。 - Lukas Kalbertodttest
和test2
有什么区别?前者期望具体类型__只有__'static
引用,而后者表示所有可能(即's
)生命周期都实现了特质Trait<'s>
,并相应地选择任何人?我有点困惑,因为我认为它们是一样的。 - vikram2784