运行说明
Circle 声明 Shape 为 supertrait,每个 Circle 也是 Shape。Unit 的 &dyn Circle 绑定直接协变成 &dyn Shape——supertrait 向上转型,Rust 1.86 起稳定——继承的 area 方法经转型引用调用。
打印的 area via upcast 为 3.14,由 Unit 的 Shape impl 计算。子 trait 保留自己的方法:unit.radius() 仍打印 1.0——向上转型拓宽接口,不丢原始绑定。
要点提示
- 向上转型作用于引用与 trait 对象,Box 默认不行。
- supertrait 约束是协变合法的前提。
核心语句
let shape: &dyn Shape = unit;
代码示例
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
}
// Circle is a subtrait: every Circle is also a Shape
trait Circle: Shape {
fn radius(&self) -> f64;
}
struct Unit;
impl Shape for Unit {
fn area(&self) -> f64 {
PI * 1.0 * 1.0
}
}
impl Circle for Unit {
fn radius(&self) -> f64 {
1.0
}
}
fn main() {
let unit: &dyn Circle = &Unit;
// supertrait upcasting: the trait object &dyn Circle coerces to &dyn Shape
let shape: &dyn Shape = unit;
println!("area via upcast: {:.2}", shape.area());
println!("radius stays on the child trait: {:.1}", unit.radius());
}