In this question:
How to get a reference to a concrete type from a trait object?
Explains how to use Any
to downcast a Trait. But I would like to downcast directly from the Trait to all the supported known types instead of using a generic as_any
method. I tried:
pub trait A{
fn as_B(&self) -> B {
(&self as &dyn Any).downcast_ref::<B>().expect("Can't cast to B").clone()
}
}
impl A for B{}
But I get the error: lifetime may not live long enough cast requires that '1
must outlive 'static
I have tried:
- Mark trait A as Clone, but this is not an option since this break other Traits that uses A and need those traits to be object traits.
- Put life time parameters in the trait. This litter a lot of places where my trait A is used and in the end I get the same compilation error.
- Remove & from self. But is neither an option since A size is not known.