将泛型参数与 impl 中的关联类型匹配

Matching a generic parameter to an associated type in an impl

我有一个具有关联类型和通用结构的特征::

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`

很公平,我必须向编译器解释 BA::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

干得好,编译器——它不是一个特质;它是一个关联类型,但并没有告诉我如何编写匹配它的 where 子句。

您可以去掉通用参数 B 而不是限制 B,直接将 A::Foo 作为第二个通用参数传递给 Baz,但我'我不确定您的实际问题是否符合您展示的简化示例。

impl<A: Generator> Baz<A, A::Foo> {
    fn addFoo(&mut self)  {
        self.vec.push(self.generator.generate());
    }
}

诀窍是只有一个通用参数:

trait Generator {
    type Foo;
    fn generate(&self) -> Self::Foo;
}

struct Baz<G>
where
    G: Generator,
{
    generator: G,
    vec: Vec<G::Foo>,
}

impl<G> Baz<G>
where
    G: Generator,
{
    fn add_foo(&mut self) {
        self.vec.push(self.generator.generate());
    }
}

由于矢量将包含 G::Foo,我们实际上可以这样说。

Rust 风格是 snake_case,所以我更新了它并制作了类型参数 G 以帮助 reader。

I must explain to the compiler that B is the same as A::Foo

它有一个特殊的语法:

impl<A, B> Baz<A, B>
where
    A: Generator<Foo = B>,
{
    fn add_foo(&mut self) {
        self.vec.push(self.generator.generate());
    }
}