rust downcast

downcast-rs = “1.2”

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

Original: https://www.cnblogs.com/pythonClub/p/16513943.html
Author: CrossPython
Title: rust downcast

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15792/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部