Thread with 2 posts
jump to expanded postI don’t know who needs to hear this, but
trait FooBar: Any {
fn as_any(&self) -> &dyn Any {
&self as &dyn Any
}
}
sadly will not work, no matter how many apostrophes you add. you also can’t just call .downcast_ref() on a FooBar.
previously, when having to do this, i just gave up.
but it turns out there’s a practical workaround:
trait FooBar: Any {}
pub trait AnyFooBar {
fn as_any<'a>(&'a self) -> &'a (dyn std::any::Any + 'static);
}
impl<T: FooBar> AnyFooBar for T {
fn as_any<'a>(&'a self) -> &'a (dyn std::any::Any + 'static) {
&*self
}
}
I hope this helps avoid suffering for someone else!
there was some interesting further discussion on Twitter: https://twitter.com/DrawsMiguel/status/1605747320590462976