How to downcast from trait object


#1
let a: Box<ClonableAction<T> + 'static> = a.clone();
let a: Box<Action<T> + 'static> = a;

note: expected type Box<Action<T> + 'static>
note: found type Box<ClonableAction<T> + 'static>

pub trait Action<T>: Debug
    where T: ActionTarget
{
}

pub trait ClonableAction<T>: Action<T>
    where T: ActionTarget
{
    fn clone(&self) -> Box<ClonableAction<T>>;
}

#2

A common question. :wink:
That’s what the Any trait is for, but for ergonomics, one still needs to implement methods on the trait that you intend to downcast. There are many crates that provide macros to implement these methods on a trait: https://crates.io/search?q=downcast

I had a long thread back in December trying to wrap my mind around why other crates used unsafe code underneath. I learned that it was unnecessary and wrote the downcast-rs crate using only safe code.