0

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>,
}
Max888
  • 3,089
  • 24
  • 55
  • 1
    You're missing the trait bound on `MyTrait: MyTraitClone` from the answer of the linked question. – cafce25 Nov 23 '22 at 00:58

0 Answers0