← 中文资源

简体中文版本

clone_box 克隆 trait 对象

Box<dyn Trait> 本身没有 Clone:给 trait 加 clone_boxed 方法并 impl Clone for Box<dyn Trait>,即可从 trait 对象重建具体类型,整个 Vec 也能克隆。

阅读英文原文

机制说明

Box 默认不可克隆——Clone 对 trait 对象不是对象安全的——所以 Shape 挂上 supertrait ShapeClone,其 clone_boxed 返回新的 Box。泛型 impl 覆盖所有 Shape + Clone 的 T,再为 Box 实现 Clone 委托给 clone_boxed。

Circle 与 Rect 都 derive Clone,Vec<Box> 因此整体可克隆:copies.clone() 经各自实现克隆每个具体类型,循环打印半径 2 的 circle area=12.57 与 3x4 的 rect area=12.00。

注意事项

  • 桥接 trait 是对象安全克隆的前提。
  • 每个 boxed 值按具体类型克隆,而不是 dyn Shape。

核心语句

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

代码示例

trait Shape: ShapeClone {
    fn area(&self) -> f64;
    fn name(&self) -> &'static str;
}

// bridge trait: every Clone + Shape trait object gets a boxed clone constructor
trait ShapeClone {
    fn clone_boxed(&self) -> Box<dyn Shape>;
}

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

// now Box<dyn Shape> itself is Clone
impl Clone for Box<dyn Shape> {
    fn clone(&self) -> Box<dyn Shape> {
        self.clone_boxed()
    }
}

#[derive(Clone)]
struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }
    fn name(&self) -> &'static str {
        "circle"
    }
}

#[derive(Clone)]
struct Rect {
    width: f64,
    height: f64,
}

impl Shape for Rect {
    fn area(&self) -> f64 {
        self.width * self.height
    }
    fn name(&self) -> &'static str {
        "rect"
    }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 2.0 }),
        Box::new(Rect { width: 3.0, height: 4.0 }),
    ];

    let copies = shapes.clone();
    for shape in &copies {
        println!("{} area={:.2}", shape.name(), shape.area());
    }
}