You could get rid of the generic argument B
and instead of constraining B
, directly pass A::Foo
as the second generic argument to Baz
, but I'm not sure if your actual problem matches the simplified example you showed.
impl<A: Generator> Baz<A, A::Foo> {
fn addFoo(&mut self) {
self.vec.push(self.generator.generate());
}
}
The trick is to only have a single generic parameter:
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());
}
}
Since the vector will contain G::Foo
, we can actually just say that.
The Rust style is snake_case
, so I updated that as well as made the type parameter G
to help the reader.
I must explain to the compiler that
B
is the same asA::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());
}
}