skip to content

In Rust 1.86 and later, how do you get a concrete `Metrics` plugin back out of a `Box<dyn Plugin>`, and what did code need before trait-object upcasting?

level: seniorimportance: should knowfreq 34%

answer

  1. Any as a supertrait
  2. coerce dyn Sub to dyn Super
  3. downcast_ref returns Option
  4. before 1.86: an as_any method

basics

~20 s

Declare trait Plugin: Any, upcast the &dyn Plugin to &dyn Any (allowed since Rust 1.86) and call downcast_ref::<Metrics>(), or upcast the Box to Box<dyn Any> and call downcast. Before 1.86 each plugin implemented an as_any(&self) -> &dyn Any method.

solid answer

~40 s

`std::any::Any` records a value's `TypeId`, and `downcast_ref`, `downcast_mut` and `Box::downcast` are inherent methods of `dyn Any`, so they cannot be called on a `&dyn Plugin` directly (E0599). Make `Any` a supertrait, `trait Plugin: Any`, and since **Rust 1.86** a trait object coerces to a supertrait object: `let any: &dyn Any = p.as_ref();` then `any.downcast_ref::<Metrics>()` returns `Option<&Metrics>`. For ownership, `let owned: Box<dyn Any> = boxed;` and `owned.downcast::<Metrics>()` returns `Result<Box<Metrics>, Box<dyn Any>>`. Before 1.86 that coercion did not exist, so each impl wrote `fn as_any(&self) -> &dyn Any { self }`. Two traps: `Any` requires `'static`, and `boxed.type_id()` returns the `TypeId` of `Box<dyn Plugin>`, not of `Metrics`.

code

rust · 28 lines
rust
use std::any::Any;

trait Plugin: Any {
    fn name(&self) -> &str;
}

struct Metrics { flushed: u32 }
struct Audit;
impl Plugin for Metrics { fn name(&self) -> &str { "metrics" } }
impl Plugin for Audit { fn name(&self) -> &str { "audit" } }

fn main() {
    let plugins: Vec<Box<dyn Plugin>> = vec![Box::new(Metrics { flushed: 7 }), Box::new(Audit)];
    for p in &plugins {
        let any: &dyn Any = p.as_ref(); // upcast &dyn Plugin -> &dyn Any (Rust 1.86+)
        match any.downcast_ref::<Metrics>() {
            Some(m) => println!("{} flushed {}", p.name(), m.flushed),
            None => println!("{} is not Metrics", p.name()),
        }
    }

    let boxed: Box<dyn Plugin> = Box::new(Metrics { flushed: 1 });
    let owned: Box<dyn Any> = boxed; // upcast the owning pointer too
    match owned.downcast::<Metrics>() {
        Ok(m) => println!("took back Metrics with {}", m.flushed),
        Err(_) => println!("not Metrics"),
    }
}

go deeper

for a junior

Recall that getting a concrete type out of a trait object is downcasting, done through std::any::Any and downcast_ref, which returns an Option.

for a middle

Explain the supertrait recipe: Plugin: Any, upcast to &dyn Any, then downcast_ref or Box::downcast. Know the 'static requirement and why the methods live on dyn Any.

for a senior

Know that upcasting arrived in Rust 1.86, recognise the as_any boilerplate it replaces, and catch the Box type_id trap in review.

for a principal

Treat each downcast as coupling to a concrete type; prefer a trait method for capabilities and limit downcasting to diagnostics, tests and deliberate integration points.

## The situation A plugin loader hands back `Vec<Box<dyn Plugin>>`. Most code only calls trait methods, but one admin screen needs the `Metrics` plugin's own `flushed` counter, a field the `Plugin` trait does not expose. Getting a concrete type back from a trait object is **downcasting**, and in Rust it goes through `std::any::Any`. ## How Any works - `Any` is a trait with one method, `type_id(&self) -> TypeId`, and a blanket impl for every `T: 'static + ?Sized`. Most types implement it automatically; a type holding a non-`'static` reference does not. - `TypeId::of::<T>()` is a unique identifier for a type, so comparing the stored id with `TypeId::of::<Metrics>()` tells whether the erased value is a `Metrics`. - The useful methods are **inherent methods on `dyn Any`** (and on `dyn Any + Send`, `dyn Any + Send + Sync`): `is::<T>()`, `downcast_ref::<T>() -> Option<&T>` and `downcast_mut::<T>() -> Option<&mut T>`. `Box<dyn Any>` adds `downcast::<T>() -> Result<Box<T>, Box<dyn Any>>`, returning the original box on a mismatch. - `Any` only tests for one concrete type. It cannot answer "does this value implement some other trait?". Because those methods belong to `dyn Any`, a `&dyn Plugin` does not have them: `r.downcast_ref::<Metrics>()` fails with **E0599**, "no method named `downcast_ref` found". You first need a `&dyn Any` that points at the same value. ## Since Rust 1.86: upcasting Rust 1.86 stabilised **trait-object upcasting**: a `dyn Sub` coerces to `dyn Super` when `Super` is one of `Sub`'s supertraits, for references, `Box`, `Rc` and `Arc` alike. So the recipe is: 1. Declare `trait Plugin: Any { fn name(&self) -> &str; }`. Every `'static` plugin type already implements `Any`, so implementors write nothing extra. 2. Coerce: `let any: &dyn Any = p.as_ref();` (from a `Box<dyn Plugin>`) or `let any: &dyn Any = r;` (from a `&dyn Plugin`). 3. Ask: `if let Some(m) = any.downcast_ref::<Metrics>() { ... }`. 4. To take ownership, coerce the box: `let owned: Box<dyn Any> = boxed;` then `owned.downcast::<Metrics>()`. Upcasting is not limited to `Any`. `trait Shape: Named + Debug` lets a `Box<dyn Shape>` become a `Box<dyn Named>`, and the coercion may drop auto traits, `dyn Plugin + Send` to `dyn Plugin`. Without the supertrait relationship the coercion is refused: `let a: &dyn Any = &*p;` for a `Plugin` that does not extend `Any` is E0308 "mismatched types", "expected trait `Any`, found trait `Plugin`". ## What a downcast does The core library's implementation is short enough to read, and it explains why the check is safe: 1. `is::<T>()` computes `TypeId::of::<T>()` for the type you asked about. 2. It calls `self.type_id()` on the `dyn Any`, which dispatches through the vtable to the concrete type's own `Any` impl and returns that type's id. 3. It compares the two ids; `downcast_ref` returns `Some` only when they are equal, and then casts the data pointer to `&T`. The comparison is sound because the blanket impl is the only `Any` impl that can exist, so no type can report a false id. Nothing is copied or converted: a successful downcast is the same pointer viewed as a concrete type. ## Before Rust 1.86: the as_any method Older code, and code that must build on an older minimum supported Rust version, adds the coercion by hand: ```rust trait Plugin { fn name(&self) -> &str; fn as_any(&self) -> &dyn Any; } impl Plugin for Metrics { fn name(&self) -> &str { "metrics" } fn as_any(&self) -> &dyn Any { self } } // p.as_any().downcast_ref::<Metrics>() ``` Inside each impl the concrete type is known, so `self` coerces to `&dyn Any` there. This still compiles today; on 1.86+ the supertrait coercion makes the boilerplate unnecessary. ## Traps | Trap | What happens | Fix | |---|---|---| | `boxed.type_id()` on a `Box<dyn Plugin>` | method lookup finds `Any` for the `Box` itself, so it returns `TypeId::of::<Box<dyn Plugin>>()` | call it on the pointee: `(&*boxed).type_id()` | | A plugin borrowing non-`'static` data | the type is not `Any`, so `Plugin: Any` excludes it | own the data, or use a different design | | Downcasting to test a capability | `Any` matches exact types only | add a trait method for the capability | ## When to reach for it Downcasting is an escape hatch. Each `downcast_ref::<Metrics>()` re-couples generic plugin code to one concrete type, and a plugin wrapped in a decorator type silently returns `None`. Prefer a trait method when every plugin could answer; keep downcasting for diagnostics, tests and genuinely type-specific integration points.

  • Why does `r.downcast_ref::<Metrics>()` not compile when `r: &dyn Plugin` and `Plugin: Any`?
    `downcast_ref` is an inherent method of `dyn Any`, not a method of the `Any` trait, so it exists only on a `dyn Any` receiver. rustc reports E0599 "no method named `downcast_ref` found". Upcast first, `let any: &dyn Any = r;`, then call it on `any`.
  • What does `Box<dyn Any>::downcast` return when the type does not match, and why that shape?
    It returns `Err(Box<dyn Any>)`, handing back the original box. The method consumes the box, so on a mismatch the caller would otherwise lose the value; returning it lets you try another type or put it back.

  • Calls downcast_ref directly on a &dyn Plugin and expects it to compile.
  • Says upcasting &dyn Sub to &dyn Super has always worked in stable Rust.
  • Thinks Any can check whether a value implements some other trait.
  • Uses boxed.type_id() on a Box<dyn Plugin> expecting the plugin's TypeId.
  • Assumes any type, including one holding a borrowed &str field, implements Any.

Assumes Rust 1.99 on edition 2024; coercing &dyn Plugin to &dyn Any relies on trait-object upcasting, stable since Rust 1.86.