Clone trait object, what did I do wrong?

I need to clone a trait object. and I found an article explaining how that could be done, but I did something wrong and I'm lost.

This is the article:
https://chaoslibrary.blot.im/rust-cloning-a-trait-object/

This is what was written:

trait MyTraitClone {
    fn clone_box(&self) -> Box<dyn DNSRecord>;
}

impl<T>  MyTraitClone for T where 
    T: 'static + DNSRecord + Clone {
        fn clone_box(&self) -> Box<dyn DNSRecord> {
            Box::new(self.clone())
        }

    }

impl Clone for Box<dyn DNSRecord> {
    fn clone(&self) -> Box<dyn DNSRecord> {
        self.clone_box()
    }
} 

What's the definition of trait DNSRecord? It's probably the problematic piece.

pub trait DNSRecord {
fn get_name(&self) -> String;
fn get_type(&self) -> u16;
fn get_class(&self) -> u16;
fn get_ttl(&self) -> u32;
fn get_rdlength(&self) -> u16;
fn get_rdata(&self) -> String;
}

There's one change the post forgot to mention (playground):

-pub trait DNSRecord {
+pub trait DNSRecord: MyTraitClone {

For dyn DNSRecord to have clone_box available, all types implementing DNSRecord must meet the bounds for MyTraitClone. I must say though, this is a very clever solution on the author's part, to indirectly require all DNSRecord types to be Clone while still letting the trait be object-safe.

2 Likes