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()));
}