use std::any::Any; use dyncast::{dyncast, DyncastExt}; #[dyncast] trait Boba { fn supper(&self); } struct A; #[dyncast] impl Boba for A { fn supper(&self) { println!("a") } } #[dyncast] impl Boba for A { fn supper(&self) { println!("i32") } } struct B; #[dyncast] impl Boba for B { fn supper(&self) { println!("b") } } #[dyncast] trait Soba {} #[dyncast] impl Soba for B {} #[test] fn boba() { let a = A; let b = B; let a = &a as &dyn Any; let b = &b as &dyn Any; a.dyncast_to::>().unwrap().supper(); a.dyncast_to::>().unwrap().supper(); b.dyncast_to::>().unwrap().supper(); assert!(a.dyncast_to::>().is_some()); assert!(a.dyncast_to::>().is_none()); assert!(a.dyncast_to::>().is_some()); assert!(a.dyncast_to::().is_none()); assert!(b.dyncast_to::>().is_some()); assert!(b.dyncast_to::>>().is_none()); assert!(b.dyncast_to::().is_some()); } #[dyncast] trait Convert { fn convert_to(&self) -> To; } struct Conv(usize); #[dyncast] impl Convert for Conv { fn convert_to(&self) -> String { format!("{}", self.0) } } #[dyncast] impl Convert for Conv { fn convert_to(&self) -> usize { self.0 } } #[test] fn convert() { let p = Box::new(Conv(1337)) as Box; let p = &*p; assert_eq!( p.dyncast_to::>().unwrap().convert_to(), 1337 ); assert_eq!( p.dyncast_to::>().unwrap().convert_to(), "1337" ); }