1

This is so far what I've tried, which doesn't really work out. I meant to have a generic function that will take a type parameter and a self parameter that is the trait object of Behaviour, and return the type as the behaviour object being casted to the type in the type parameter. And besides, I've thought of using pattern matching at runtime that will only produce an output if the type matches, however I've got the error of mismatched types between <&Behaviour> and <T>.

pub trait Behaviour: BehaviourAgent {
    fn set(&mut self) -> ();
}

pub trait BehaviourAgent {
    fn clone_agent(&self) -> Box<Behaviour>;
    // fn revert<_type>(&self) -> _type;
}

impl<Type> BehaviourAgent for Type where Type: 'static + Behaviour + Clone, {
    fn clone_agent(&self) -> Box<Behaviour> {
        return Box::new(self.clone());
    }
}

impl Clone for Box<Behaviour> {
    fn clone(&self) -> Box<Behaviour> {
        return self.clone_agent();
    }
}

pub trait TypeRevert<Type> {
    fn revert(&mut self) -> Type;
}

// impl<Type> TypeRevert<Type> for & 'static Behaviour {
//  fn revert(&mut self) -> Type {
//      unsafe { return self.clone(); }
//  }
// }

impl<Type> TypeRevert<Type> for Type where Type: 'static + Behaviour + Clone {
    fn revert(&mut self) -> Type {
        return self.clone();
    }
}

#[derive(Clone, Copy)]
pub struct SoundDevice {/*attributes*/}

impl Behaviour for SoundDevice {
    fn set(&mut self) -> () { }
}

fn main() {
    let target: Box<Behaviour> = Box::new(SoundDevice { });
    // let mut test_obj: SoundDevice = TypeRevert::revert(&mut *(target.clone()));
    let mut test_obj: SoundDevice = TypeRevert::<SoundDevice>::revert(&mut *(target.clone()));
}
Chaffon Liu
  • 323
  • 4
  • 7
  • I believe your question is answered by the answers of [How to get a struct reference from a boxed trait?](https://stackoverflow.com/q/33687447/155423); [Can I do type introspection with trait objects and then downcast it?](https://stackoverflow.com/q/27892375/155423); etc.. If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Sep 24 '18 at 23:12
  • 1
    Thank you very much, i can confirm [How to get a struct reference from a boxed trait?](https://stackoverflow.com/questions/33687447/how-to-get-a-struct-reference-from-a-boxed-trait) is relevant, since my aim here is to verify the type of a trait object, it pretty much answers my question, feel free to mark this as a duplicate @Shepmaster – Chaffon Liu Sep 25 '18 at 03:55

0 Answers0