我有一个具有关联类型和通用结构的特征::
trait Generator {
type Foo;
fn generate(&self) -> Self::Foo;
}
struct Baz<A, B>
where
A: Generator,
{
generator: A, // will be some struct implementing Generator, but the exact type will vary
vec: Vec<B>, // Each element will be A::Foo
}
我想要generate
并将其放入我的向量中:
impl<A: Generator, B> Baz<A, B> {
fn addFoo(&mut self) {
self.vec.push(self.generator.generate());
}
}
呃-哦!编译错误:
error[E0308]: mismatched types
--> src/main.rs:16:27
|
16 | self.vec.push(self.generator.generate());
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter, found associated type
|
= note: expected type `B`
found type `<A as Generator>::Foo`
公平地说,我必须向编译器解释一下B
是相同的A::Foo
;让我们尝试一下where
:
impl<A: Generator, B> Baz<A, B>
where
A::Foo = B,
{
这没有帮助:
error: equality constraints are not yet supported in where clauses (#20041)
--> src/main.rs:16:5
|
16 | A::Foo = B,
| ^^^^^^^^^^
嗯,没有平等。也许我可以用冒号运算符来做到这一点?
impl<A: Generator, B> Baz<A, B>
where
B: A::Foo,
{
error[E0405]: cannot find trait `Foo` in `A`
--> src/main.rs:16:11
|
16 | B: A::Foo,
| ^^^ not found in `A`
不,现在它在抱怨A
。也许我应该说Generator
?
impl<A: Generator, B> Baz<A, B>
where
B: Generator::Foo,
{
error[E0404]: expected trait, found associated type `Generator::Foo`
--> src/main.rs:16:8
|
16 | B: Generator::Foo,
| ^^^^^^^^^^^^^^ not a trait
干得好,编译器——它是not一个特质;它是一个关联类型,但这并没有告诉我如何编写与其匹配的 where 子句。