机制说明
Box
Circle 与 Rect 都 derive Clone,Vec<Box
注意事项
- 桥接 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());
}
}