Implement Clone for Box<dyn MyTrait> with generic type

I can implement Clone for trait with type parameters like this:


trait MyTrait<T>: MyTraitClone<T> {}

trait MyTraitClone<T> {
    fn trait_clone(&self) -> Box<dyn MyTrait<T>>;
}

impl<T: Clone + MyTrait<K> + 'static, K> MyTraitClone<T> for T {
    fn trait_clone(&self) -> Box<dyn MyTrait<K>> {
        Box::new(self.clone())
    }
}

impl<T> Clone for Box<dyn MyTrait<T>> {
    fn clone(&self) -> Self {
        self.trait_clone()
    }
}

But if MyTrait has associated type, I try to implement Clone like this(playground), it can not work:

trait MyTrait: MyTraitClone { type T; }

trait MyTraitClone {
    fn trait_clone<T>(&self) -> Box<dyn MyTrait<T = T>>;
}

impl<T: Clone + MyTrait<T = K> + 'static, K> MyTraitClone for T {
    fn trait_clone<N>(&self) -> Box<dyn MyTrait<T = N>> {
        Box::new(self.clone())
    }
}

impl<T> Clone for Box<dyn MyTrait<T = T>> {
    fn clone(&self) -> Self {
        self.trait_clone::<T>()
    }
}

What should I do?

1 Like

You might want to check out this crate: dyn-clonable

2 Likes

Thanks for your reply. I've tried dyn-clonable, it has following error:

#[clonable]
trait MyTrait: Clone {
    type A;
    fn recite(&self);
}

[E0191] Error: the value of the associated type `A` (from trait `MyTrait`) must be specified
   โ•ญโ”€[command_49:1:1]
   โ”‚
 2 โ”‚ trait MyTrait: Clone {
   ยท       โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€  
   ยท          โ•ฐโ”€โ”€โ”€โ”€โ”€ error: the value of the associated type `A` (from trait `MyTrait`) must be specified
   ยท          โ”‚     
   ยท          โ•ฐโ”€โ”€โ”€โ”€โ”€ help: specify the associated type: `MyTrait<A = Type>`
 3 โ”‚     type A;
   ยท     โ”€โ”€โ”€โ”ฌโ”€โ”€  
   ยท        โ•ฐโ”€โ”€โ”€โ”€ `A` defined here
โ”€โ”€โ”€โ•ฏ

The more popular dyn cloning crate is dyn_clone - Rust

I can try some stuff and write a longer answer later today.

1 Like

So, just doing

use dyn_clone::{clone_trait_object, DynClone};

pub trait MyTrait: DynClone {
    type T;
}

clone_trait_object!(<T> MyTrait<T = T>);

seems to work.

I couldnโ€™t come up with any workable purely-safe-Rust alternative solutions yet, but even if they exist, just using dyn_clone is presumably more convenient anyways.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.