Created
May 17, 2019 20:54
-
-
Save sketchpunk/10ab0ffac252e44767add21276d2b531 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::any::Any; | |
use std::marker::PhantomData; | |
//#################################################### | |
struct Test{ data: Box<dyn Any> } | |
#[derive(Default, Debug)] | |
struct Pos{ x: f32 } | |
#[derive(Default, Debug)] | |
struct Rot{ z: f32 } | |
//#################################################### | |
fn main() { | |
let t = Test{ data: Box::new( Pos::default() ) }; | |
println!("t.data = {:?}", t.data ); // Its Any | |
// Straight From Any | |
let p = t.data.downcast_ref::<Pos>().unwrap(); | |
println!("A: {:?}", p ); // its Pos! | |
// Create Struct that hold T that can then downcast | |
let d = DCast::<Pos>::new(); | |
println!( "B: {:?}", d.downcast( &t.data ).unwrap() ); | |
// Create a Generic function and save it for later down casting | |
let f : F<Pos> = d_cast; | |
println!( "C: {:?}", f( &t.data ).unwrap() ); | |
let ff : F<Rot> = d_cast; | |
println!( "D: {:?}", ff( &t.data ) ); | |
} | |
//#################################################### | |
struct DCast<T>{ | |
_marker: PhantomData<*const T>, | |
} | |
impl<T:'static> DCast<T>{ | |
fn new() -> DCast<T>{ DCast{ _marker: PhantomData, } } | |
fn downcast<'a>( &self, a: &'a Box<Any> ) -> Option<&'a T>{ | |
a.downcast_ref::< T >() | |
} | |
} | |
//#################################################### | |
type F<T> = fn( a: &Box<Any> ) -> Option<&T>; | |
fn d_cast<T:'static>( a: &Box<Any> ) -> Option<&T>{ | |
a.downcast_ref::<T>() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment