Wie kann eine Struktur geklont werden, in der ein Objekt mit geschachtelten Merkmalen gespeichert ist?

Ich habe ein Programm geschrieben, das das Merkmal hatAnimal und die structDog Umsetzung des Merkmals. Es hat auch eine StrukturAnimalHouse Speichern eines Tieres als Merkmal ObjektBox<Animal>.

trait Animal {
    fn speak(&self);
}

struct Dog {
    name: String,
}

impl Dog {
    fn new(name: &str) -> Dog {
        return Dog {
            name: name.to_string(),
        };
    }
}

impl Animal for Dog {
    fn speak(&self) {
        println!{"{}: ruff, ruff!", self.name};
    }
}

struct AnimalHouse {
    animal: Box<Animal>,
}

fn main() {
    let house = AnimalHouse {
        animal: Box::new(Dog::new("Bobby")),
    };
    house.animal.speak();
}

It gibt "Bobby: Halskrause, Halskrause!" wie erwartet, aber wenn ich versuche, @ zu klonhouse Der Compiler gibt Fehler zurück:

fn main() {
    let house = AnimalHouse {
        animal: Box::new(Dog::new("Bobby")),
    };
    let house2 = house.clone();
    house2.animal.speak();
}
error[E0599]: no method named `clone` found for type `AnimalHouse` in the current scope
  --> src/main.rs:31:24
   |
23 | struct AnimalHouse {
   | ------------------ method `clone` not found for this
...
31 |     let house2 = house.clone();
   |                        ^^^^^
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `clone`, perhaps you need to implement it:
           candidate #1: `std::clone::Clone`

Ich habe versucht, @ hinzuzufüg#[derive(Clone)] Vorstruct AnimalHouse und bekam einen weiteren Fehler:

error[E0277]: the trait bound `Animal: std::clone::Clone` is not satisfied
  --> src/main.rs:25:5
   |
25 |     animal: Box<Animal>,
   |     ^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` is not implemented for `Animal`
   |
   = note: required because of the requirements on the impl of `std::clone::Clone` for `std::boxed::Box<Animal>`
   = note: required by `std::clone::Clone::clone`

Wie mache ich die StrukturAnimalHouse klonbar? Ist es idiomatisch, ein Merkmalsobjekt generell aktiv zu nutzen?

Antworten auf die Frage(6)

Ihre Antwort auf die Frage