[solved] Is it possible to clone a boxed trait object?

Here is an improved solution for anyone who comes across this. I changed BoxClone to CloneFoo because it is specific to Foo. Also you don't have to re-implement CloneFoo for every derived struct.

trait Foo: CloneFoo {}

#[derive(Clone)]
struct Bar;

impl Foo for Bar {}

trait CloneFoo {
    fn clone_foo<'a>(&self) -> Box<dyn Foo>;
}

impl<T> CloneFoo for T
where
    T: Foo + Clone + 'static,
{
    fn clone_foo(&self) -> Box<dyn Foo> {
        Box::new(self.clone())
    }
}

impl Clone for Box<dyn Foo> {
    fn clone(&self) -> Self {
        self.clone_foo()
    }
}
8 Likes