Rust Dyn Clone crate

Clone traits object without using unsafe compared to dyn-clone
clonable_trait_object

cargo add clonable_trait_object
use clonable_trait_object::clonable_trait_object;

/*El primer parametro es el trait objetivo
el segundo parametro es el nombre que le daras al trait 
que hara de Clone*/ 
clonable_trait_object!(Animal,AnimalClone);
trait Animal: AnimalClone {
 fn speak(&self);
}
#[derive(Clone,Debug)]
struct Dog {
 name: String,
}
impl Dog {
 fn new(name: &str) -> Dog {
     Dog {
         name: name.to_string(),
     }
 }
}
impl Animal for Dog {
 fn speak(&self) {
     println!("{}: ruff, ruff!", self.name);
 }
}
#[derive(Clone)]
struct AnimalHouse {
 animal: Box<dyn Animal>,
}
fn main() {
 let house = AnimalHouse {
     animal: Box::new(Dog::new("Bobby")),
 };
 let house2 = house.clone();
 house2.animal.speak();
}

Translation:

The first parameter is the trait object [and] the second parameter is the name that you will give to the trait that will implement[1] Clone.


Hablo castellano jaja :sunglasses:


  1. hará, 3rd person singular conjugation of the simple future of hacer, meaning "he/she/it will do": I just thought "implement Clone" would fit a little better here than "do Clone or "do the Cloneing" ↩︎

1 Like

yo igual jaja

1 Like

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.