trait-concept

Rust Supertrait access before Rust 1.86

Direct trait-object upcasting became stable in Rust 1.86, after our proposed 1.85 baseline. On the baseline, a dyn-compatible adapter method can return a supertrait object by coercing a concrete reference inside its implementation. Calling a supertrait method directly on the subtrait object does not require this conversion. Expected output (not executed): lamp Why: Inside Lamp’s implementation the compiler knows the concrete type, so coercion to &dyn Named is available. Common mistake: Using let base: &dyn Named = device on stable 1.85 and expecting native upcasting support.

Formal Syntax & Structure

rust syntaxrust
fn as_base(&self) -> &dyn Base

Working Example

Example Snippetrust
trait Named { fn name(&self) -> &str; }trait Device: Named { fn as_named(&self) -> &dyn Named; }struct Lamp;impl Named for Lamp { fn name(&self) -> &str { "lamp" } }impl Device for Lamp { fn as_named(&self) -> &dyn Named { self } }fn show(value: &dyn Named) { println!("{}", value.name()); }fn main() {    let device: &dyn Device = &Lamp;    show(device.as_named());}
Rust Reference