Trait Object Upcasting To Supertraits

Since Rust 1.86 a trait object reference coerces to any supertrait: &dyn Circle flows into &dyn Shape and the inherited area method stays callable.

RustData Integrity

Code

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

What the demo upcasts

Circle declares Shape as its supertrait, so every Circle is also a Shape. A &dyn Circle binding of the Unit type coerces directly into &dyn Shape, supertrait upcasting stabilized in Rust 1.86, and the inherited area method runs through the upcast reference.

The printed area via upcast is 3.14, computed by the Shape impl for Unit. The child trait keeps its own method: unit.radius() still prints 1.0, showing that upcasting widens the interface without losing the original binding.

Practical notes

  • Upcasting works on references and trait objects, not on Box by default.
  • The supertrait bound is what makes the coercion legal.

Interactive Tools for This Topic

FAQ

What does supertrait upcasting allow?
A &dyn Circle flows into &dyn Shape with no explicit conversion; the demo prints the area through the upcast reference while the child binding keeps calling radius.