我想了解如何多态性使用时有效具有相关类型的特征。考虑以下特征:
trait Animal {
fn talk (&self);
}
此特征由以下结构使用:
struct Dog;
struct Cow;
impl Animal for Dog {
fn talk (&self) {
println!("Woof");
}
}
impl Animal for Cow {
fn talk (&self) {
println!("Moo");
}
}
然后我循环一个Vec<&Animal>
,多态性在这里效果很好:
fn main() {
let animals: Vec<&Animal> = vec![&Dog, &Cow];
for animal in &animals {
animal.talk();
}
}
// output:
// Woof
// Moo
到目前为止,一切都很好。现在我添加关联类型 Food
到特征(不使用类型,但仅用于最小重现)。
struct Meat;
struct Herb;
trait Animal {
type Food;
...
}
impl Animal for Dog {
type Food = Meat;
...
}
impl Animal for Cow {
type Food = Herb;
...
}
现在我收到错误:
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>`
但在这种情况下,我不能只关注错误消息,因为struct
s 实现特质Animal
不应该是静态的。
Rust 解决这个问题的方法是什么?提前致谢