The parameter type `T` may not live long enough Any::downcast_ref

I've been playing around with Any and have written the following code:

pub trait Entity{

pub trait AsAnyOtherEntity<'a> {
    fn as_any_entity<T: 'a + Entity>(&'a self) -> Option<&T>;

impl<'a, U: Any + Entity> AsAnyOtherEntity<'a> for U{
    fn as_any_entity<T: 'a + Entity>(&'a self) -> Option<&T> {
        let a: &dyn Any = self;

And Rust compiler responds by telling me this:

error[E0310]: the parameter type `T` may not live long enough
  --> src/
14 |         a.downcast_ref()
   |         ^^^^^^^^^^^^^^^^ that the type `T` will meet its required lifetime bounds
help: consider adding an explicit lifetime bound...
12 |     fn as_any_entity<T: 'a + Entity + 'static>(&'a self) -> Option<&T> {
   |                                     +++++++++

Considering the fact that I have added explicit lifetime bound I'm not really sure what's happening.

The lifetime bound you added isn't 'static. It must be 'static in order for downcasting to work.

And return value of downcast_ref has 'static lifetime too?

Why not check it yourself? The return type has the Any bound, which in turn requires 'static.

The trait Any, which downcast_ref relies on, is only implemented for 'static types.

The returned type lifetime will be whatever the input lifetime is (usually not 'static) as per the lifetime elision rules.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.