extern crate downcast; use downcast::{downcast, Any}; use std::fmt::Debug; /* Trait */ trait Animal: Any { fn what_am_i(&self); fn get_item(&self) -> Option<&X>; } downcast!( dyn Animal where X: Debug); /* Impl */ struct Bird{ item: Option } impl Animal for Bird { fn what_am_i(&self){ println!("Im a bird!") } fn get_item(&self) -> Option<&X> { match self.item { Some(ref item) => println!("I'm holding a {:?}! Look, see!", item), None => println!("I'm holding nothing!") } self.item.as_ref() } } impl Bird { fn eat_item(&mut self) { if self.item.is_some() { let item = self.item.take().unwrap(); println!("I ate the {:?}! I hope it was edible!", item) } else { println!("I don't have anything to eat!") } } } /* Main */ fn main() { let mut animal: Box> = Box::new(Bird{ item: Some("haselnut".to_owned()) }); animal.what_am_i(); { let bird = animal.downcast_mut::>().unwrap(); bird.get_item(); bird.eat_item(); } let mut bird = animal.downcast::>().ok().unwrap(); bird.get_item(); bird.eat_item(); }