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>()); }

  

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/276635.html

(0)
上一篇 2022年7月24日 10:36
下一篇 2022年7月24日 10:36

相关推荐

发表回复

登录后才能评论