Downcast_ref() not working on a trait that *does* inherit from Any

⚓ Rust    📅 2026-01-20    👤 surdeus    👁️ 7      

surdeus

I have a trait that is defined like this:

pub trait MyTrait: Any + Send { ... }

Application will implement this trait:

struct MyImplementation;

impl MyTrait for MyImplementation { ... }

...and pass its implementation to my library:

fn register(&mut self, callbacks: impl MyTrait) { ... }

The instance is stored in a Box<dyn MyTrait> inside of my library:

struct MyLibrary {
    registered: Box<dyn MyTrait>,
}

Now, if I later return the Box<dyn MyTrait> back to the application, how I can convert it back to the concrete type? Specifically, how can I get the MyImplementation out of the box?

I don't understand why this does not work:

let my_ref: &dyn MyTrait = boxed_value.as_ref();
let x: Option<&MyImplementation> = my_ref.downcast_ref(); // <-- ERROR

MyTrait inherits from Any, so why I cannot call downcast_ref() on the &dyn MyTrait reference? The method downcast_ref() shall be available in a type that implements Any, which is also true for any type that implements MyTrait, since MyTrait extends Any.


Strange enough, it does work if I do:

let my_ref: &dyn MyTrait = boxed_value.as_ref();
let any_ref = my_ref as &dyn Any;
let x: Option<&MyImplementation> = any_ref.downcast_ref(); // <-- OK

But this requires Rust 1.86 or newer. Older Rust says the cast to &dyn Any is not allowed!

Why is the cast even needed?

And is there any "clean" way to do that in older Rust versions too?

Regards.

7 posts - 4 participants

Read full topic

🏷️ Rust_feed