trait Actor{
fn actor(&self);
}
trait Health{
fn health(&self);
}
struct Plant;
impl Actor for Plant{
fn actor(&self){
println!("Plant Actor");
}
}
struct Monster{
health: f32
}
impl Actor for Monster{
fn actor(&self){
println!("Monster Actor");
}
}
impl Health for Monster{
fn health(&self){
println!("Health: {}",self.health);
}
}
fn main() {
let plant = Box::new(Plant);
let monster = Box::new(Monster{health: 100f32});
let mut actors : Vec<Box<Actor>> = Vec::new();
actors.push(plant);
actors.push(monster);
for a in &actors{
a.actor();
/* Would this be possible?
let health = a.get_trait_object::<Health>();
match health{
Some(h) => {h.health();},
None => {println!("Has no Health trait");}
}
*/
}
}
I am wondering if something like this could be possible?
let health = a.get_trait_object::<Health>();
match health{
Some(h) => {h.health();},
None => {println!("Has no Health trait");}
}
See Question&Answers more detail:os