rust downcast

downcast-rs = "1.2"



// Can call macro via namespace since rust 1.30. use downcast_rs::Downcast; use std::fmt::Debug; // To create a trait with downcasting methods, extend `Downcast` or `DowncastSync` // and run `impl_downcast!()` on the trait. trait Base<T: Clone>: Downcast { type H: Copy; } downcast_rs::impl_downcast!(Base<T> assoc H where T: Clone, H: Copy); // or: impl_downcast!(concrete Base<u32> assoc H=f32) // Concrete types implementing Base. #[derive(Debug)] struct Foo(u32); impl Base<u32> for Foo { type H = f32; } #[derive(Debug)] struct Bar(f64); impl Base<u32> for Bar { type H = f32; } fn main() { // Create a trait object. let mut base: Box<dyn Base<u32, H=f32>> = Box::new(Bar(42.0)); // Try sequential downcasts. if let Some(x) = base.downcast_ref::<Foo>() { println!("111111: {:?}", x); // assert_eq!(foo.0, 42); } else if let Some(y) = base.downcast_ref::<Bar>() { println!("22222: {:?}", y); // assert_eq!(bar.0, 42.0); } assert!(base.is::<Bar>()); }

  

posted @ 2022-07-24 09:53  CrossPython  阅读(92)  评论(0编辑  收藏  举报