将通用参数与impl中的关联类型进行匹配 [英] Matching a generic parameter to an associated type in an impl
问题描述
我有一个关联类型和一个泛型结构的特征::
I have a trait with an associated type and a generic struct::
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
并将其放入我的向量中:
I want to generate
and put it into my vector:
impl<A: Generator, B> Baz<A, B> {
fn addFoo(&mut self) {
self.vec.push(self.generator.generate());
}
}
呃 - 哦!编译错误:
$ b
Uh-oh! Compile error:
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 $ c相同$ C>;让我们用
来尝试:
Fair enough, I must explain to the compiler that B
is the same as A::Foo
; let's try with where
:
impl<A: Generator, B> Baz<A, B>
where
A::Foo = B,
{
这不会有帮助:
which doesn't help:
error: equality constraints are not yet supported in where clauses (#20041)
--> src/main.rs:16:5
|
16 | A::Foo = B,
| ^^^^^^^^^^
嗯,不等于。也许我可以用冒号操作符来做到这一点吗?
Hmm, no equals. Maybe I can do this with the colon operator instead?
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
?
Nope, now it's complaining about A
. Maybe I should say 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子句。
Well good work, compiler — it's not a trait; it's an associated type, but that doesn't tell me how to write a where clause that matches it.
推荐答案
我必须向编译器解释
B
与A :: Foo
它有一个特殊的语法:
There is a special syntax for it:
impl<A, B> Baz<A, B>
where
A: Generator<Foo = B>,
{
fn add_foo(&mut self) {
self.vec.push(self.generator.generate());
}
}
这篇关于将通用参数与impl中的关联类型进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!