请考虑以下代码:
trait Animal {
fn make_sound(&self) -> String;
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) -> String {
"meow".to_string()
}
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) -> String {
"woof".to_string()
}
}
fn main () {
let dog: Dog = Dog;
let cat: Cat = Cat;
let v: Vec<Animal> = Vec::new();
v.push(cat);
v.push(dog);
for animal in v.iter() {
println!("{}", animal.make_sound());
}
}
Run Code Online (Sandbox Code Playgroud)
编译器告诉我这v是Animal我尝试推送时的向量cat(类型不匹配)
那么,我如何制作属于特征的对象向量并在每个元素上调用相应的特征方法呢?
我想在一个中使用特征对象Vec.在C++中我可以使一个基类Thing从中导出Monster1和Monster2.然后我可以创建一个std::vector<Thing*>.Thing对象必须存储一些数据,例如x : int, y : int,派生类需要添加更多数据.
目前我有类似的东西
struct Level {
// some stuff here
pub things: Vec<Box<ThingTrait + 'static>>,
}
struct ThingRecord {
x: i32,
y: i32,
}
struct Monster1 {
thing_record: ThingRecord,
num_arrows: i32,
}
struct Monster2 {
thing_record: ThingRecord,
num_fireballs: i32,
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个ThingTrait与方法get_thing_record(),attack(),make_noise()等,并实现它们的Monster1和Monster2.