Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::rc::Rc;
- use std::any::Any;
- struct Test1;
- struct Test2;
- impl Test for Test1 {
- fn test(&self) -> i16 {
- return 1;
- }
- }
- impl Test for Test2 {
- fn test(&self) -> i16 {
- return 2;
- }
- }
- impl MTest for Test2 {
- fn m_test(&self) -> i32 {
- return 3;
- }
- }
- trait Test {
- fn test(&self) -> i16;
- }
- trait MTest: Test {
- fn m_test(&self) -> i32;
- }
- trait Converter {
- type T: ?Sized;
- type O;
- fn convert(b: Rc<Any>) -> Option<Rc<Self::T>>;
- }
- struct Test1Converter;
- impl Converter for Test1Converter {
- type T = Test;
- type O = Test1;
- fn convert(b: Rc<Any>) -> Option<Rc<Self::T>> {
- if let Ok(d) = Rc::downcast::<Self::O>(b) {
- Some(d as Rc<Self::T>)
- } else { None }
- }
- }
- struct Test2Converter;
- impl Converter for Test2Converter {
- type T = Test;
- type O = Test2;
- fn convert(b: Rc<Any>) -> Option<Rc<Self::T>> {
- if let Ok(d) = Rc::downcast::<Self::O>(b) {
- Some(d as Rc<Self::T>)
- } else { None }
- }
- }
- struct Test2MConverter;
- impl Converter for Test2MConverter {
- type T = MTest;
- type O = Test2;
- fn convert(b: Rc<Any>) -> Option<Rc<Self::T>> {
- if let Ok(d) = Rc::downcast::<Self::O>(b) {
- Some(d as Rc<Self::T>)
- } else { None }
- }
- }
- fn get<Conv: Converter>(vec: &Vec<Rc<Any>>, i: usize) -> Rc<Conv::T> {
- Conv::convert(vec[i].clone()).unwrap()
- }
- fn main() {
- let mut vec : Vec<Rc<Any>> = Vec::new();
- vec.push(Rc::new(Test1));
- vec.push(Rc::new(Test2));
- println!("{}", get::<Test1Converter>(&vec, 0).test());
- println!("{}", get::<Test2Converter>(&vec, 1).test());
- println!("{}", get::<Test2MConverter>(&vec, 1).m_test());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement