面试题答案
一键面试trait Animal {
fn movement(&self);
}
struct Mammal;
struct Bird;
struct Dog;
struct Eagle;
impl Animal for Mammal {
fn movement(&self) {
println!("Mammal moves in a general way.");
}
}
impl Animal for Bird {
fn movement(&self) {
println!("Bird flies.");
}
}
impl Animal for Dog {
fn movement(&self) {
println!("Dog runs.");
}
}
impl Animal for Eagle {
fn movement(&self) {
println!("Eagle soars.");
}
}
fn describe_movement(animal: &dyn Animal) {
if let Some(dog) = animal.downcast_ref::<Dog>() {
<Mammal as Animal>::movement(&Mammal);
} else if let Some(eagle) = animal.downcast_ref::<Eagle>() {
<Bird as Animal>::movement(&Bird);
}
}
fn main() {
let dog = Dog;
let eagle = Eagle;
describe_movement(&dog);
describe_movement(&eagle);
}