相关疑难解决方法(0)

如何克隆存储盒装特征对象的结构?

我编写了一个程序,它具有特征AnimalDog实现特征的结构.它还有一个AnimalHouse存储动物作为特征对象的结构Box<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();
}
Run Code Online (Sandbox Code Playgroud)

它返回"Bobby:ruff,ruff!" 正如所料,但如果我尝试克隆house编译器返回错误:

fn main() {
    let house …
Run Code Online (Sandbox Code Playgroud)

struct clone traits cloneable rust

20
推荐指数
3
解决办法
3891
查看次数

标签 统计

clone ×1

cloneable ×1

rust ×1

struct ×1

traits ×1