I have a struct containing a trait object and I would like to be able to derive Clone
on the struct.
trait MyTrait {}
#[derive(Clone)]
pub struct Container {
trait_object: Box<dyn MyTrait>,
}
I have tried Box<dyn MyTrait + Clone>
but that isn't allowed. I also tried to adapt the answer from this similar question: How to clone a struct storing a boxed trait object? as per below but I am getting errors because the method `clone_box` exists for reference `&Box<(dyn MyTrait + 'static)>`, but its trait bounds were not satisfied
.
trait MyTrait {}
trait MyTraitClone {
fn clone_box(&self) -> Box<dyn MyTrait>;
}
impl<T> MyTraitClone for T
where
T: 'static + MyTrait + Clone,
{
fn clone_box(&self) -> Box<dyn MyTrait> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn MyTrait> {
fn clone(&self) -> Box<dyn MyTrait> {
self.clone_box()
}
}
#[derive(Clone)]
pub struct Container {
trait_object: Box<dyn MyTrait>,
}