1extern crate downcast;
2
3// we need to use downcast::Any instead of std::any::Any
4use downcast::{downcast, Any};
5
6/* Trait */
7
8trait Animal: Any {
9 fn what_am_i(&self);
10}
11
12downcast!(dyn Animal);
13
14/* Impl */
15
16struct Bird;
17
18impl Animal for Bird {
19 fn what_am_i(&self){
20 println!("Im a bird!")
21 }
22}
23
24impl Bird {
25 fn wash_beak(&self) {
26 println!("Beak has been washed! What a clean beak!");
27 }
28}
29
30/* Main */
31
32fn main() {
33 let animal: Box<dyn Animal> = Box::new(Bird);
34 animal.what_am_i();
35 {
36 let bird = animal.downcast_ref::<Bird>().unwrap();
37 bird.wash_beak();
38 }
39 let bird: Box<Bird> = animal.downcast::<Bird>().ok().unwrap();
40 bird.wash_beak();
41}
42