Clone Trait Objects With Clone Box

Box<dyn Trait> has no Clone, so a clone_boxed method plus impl Clone for the boxed object rebuilds each concrete type and whole Vecs become cloneable.

RustData Integrity

Code

rustsnippet
66 lines
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());
    }
}

What the demo clones

Box cannot be cloned by default because Clone is not object-safe for trait objects, so Shape gets a supertrait ShapeClone whose clone_boxed returns a fresh Box. A blanket impl covers every T that is Shape + Clone, and impl Clone for Box delegates to clone_boxed.

Circle and Rect both derive Clone, so the Vec<Box> becomes fully cloneable: copies.clone() duplicates each concrete type through its own clone impl, and the loop prints circle area=12.57 for the radius-2 circle and rect area=12.00 for the 3x4 rectangle.

Points to remember

  • The bridge trait is what makes the object-safe clone possible.
  • Each boxed value clones as its concrete type, not as dyn Shape.

Interactive Tools for This Topic

FAQ

Why is Clone not implemented for Box<dyn Trait> automatically?
Clone's output type is Self, which is unknowable for dyn Trait; the clone_boxed bridge returns Box<dyn Shape> instead, sidestepping the Self problem.