I want to clone a Box<dyn Trait<'a,A>. This question is similar to:
How can I clone a Vec<Box>? How to clone a struct storing a boxed trait object?
I have coded a similar solution for my problem, but I'm working with generics and associated types, and I'm having problems putting all together.
I give an example of the code I'm struggling to compile:
trait CTrait<'c> {
fn do_C(&self) -> &'c str;
}
trait BTrait<'c> {
type C : CTrait<'c>;
fn do_B(&self) -> &'c str;
}
trait ATrait<'c, C : CTrait<'c>>: CloneATrait {
type B: BTrait<'c, C=C>;
fn do_A(&self) -> &'c str;
}
trait CloneATrait {
fn clone_box<'c, C : CTrait<'c>, B : BTrait<'c, C = C>>(&self) -> Box<dyn ATrait<'c,C,B=B>>;
}
impl<'c, C : CTrait<'c>, T> CloneATrait for T
where
T: 'static + ATrait<'c,C> + Clone,
{
fn clone_box(&self) -> Box<dyn ATrait<'c,C,B = T::B>> {
Box::new(self.clone())
}
}
impl<'c, C : CTrait<'c>, B : BTrait<'c, C = C>> Clone for Box<dyn ATrait<'c,C,B=B>> {
fn clone(&self) -> Box<dyn ATrait<'c,C,B=B>> {
self.clone_box()
}
}
#[derive(Clone)]
struct MultiA<'c, B : BTrait<'c>> {
comps: Vec<Box<dyn ATrait<'c,B::C,B=B>>>,
}
impl<'c, B : BTrait<'c>> MultiA<'c,B> {
fn new(comps: Vec<Box<dyn ATrait<'c,B::C,B=B>>>) -> Self {
Self {
comps
}
}
}
impl<'c, B : BTrait<'c>> ATrait<'c,B::C> for MultiA<'c,B> {
type B = B;
fn do_A(&self) -> &'c str{
for a in &self.comps{
a.do_A();
}
self.comps[0].do_A()
}
}
fn main() {
}
I've already asked that question in Stackoverflow(/questions/73127086/clone-boxdyn-traita-a) (sorry I'm only allowed to put two links) but maybe I'm luckier in this rust dedicated forum.