I am trying to understand how polymorphism works when using a trait with an associated type. Consider the following trait:
trait Animal {
fn talk (&self);
}
This trait is used by the following structures:
struct Dog;
struct Cow;
impl Animal for Dog {
fn talk (&self) {
println!("Woof");
}
}
impl Animal for Cow {
fn talk (&self) {
println!("Moo");
}
}
Then I loop over a Vec<&Animal>, and polymorphism works well here:
fn main() {
let animals: Vec<&Animal> = vec![&Dog, &Cow];
for animal in &animals {
animal.talk();
}
}
// output:
// Woof
// Moo
So far so good. Now, I add an associated type Food to the trait (the type is not used, but it is only for the minimal repro).
struct Meat;
struct Herb;
trait Animal {
type Food;
...
}
impl Animal for Dog {
type Food = Meat;
...
}
impl Animal for Cow {
type Food = Herb;
...
}
And now I get the error:
error[E0191]: the value of the associated type `Food` (from trait `Animal`) must be specified
--> src/main.rs:188:23
163 | type Food;
| ---------- `Food` defined here
...
188 | let animals: Vec<&Animal> = vec![&Dog, &Cow];
| ^^^^^^ help: specify the associated type: `Animal<Food = Type>`
But in this case, I cannot just follow the error message since the number of structs implementing the trait Animal is not supposed to be static.
What is the Rust way to solve that ? Thanks in advance