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.
Code
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
Circle and Rect both derive Clone, so the Vec<Box
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
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.