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/
转载文章受原作者版权保护。转载请注明原作者出处!