How to downcast from a trait + Any to a struct


#1

I have a trait LibVal that inherits the Any trait. But when I try to downcast from my LibVal trait to a struct that implements LibVal, I get the following compile error:

error[E0308]: mismatched types
   --> src/leema/val.rs:587:40
    |
587 |                 Any::downcast_ref::<T>(&**lvref)
    |                                        ^^^^^^^^ expected trait `std::any::Any`, found trait `leema::val::LibVal`
    |
    = note: expected type `&std::any::Any + 'static`
               found type `&leema::val::LibVal + 'static`

My LibVal trait is defined like:

pub trait LibVal
    : Any
    + Debug
{
    fn get_type(&self) -> Type;
}

And the function where I get the compile error is:

pub fn libval_as<T>(&self) -> Option<&T>
    {
        match self {
            &Val::Lib(ref lvref) => {
                Any::downcast_ref::<T>(&**lvref)
            }
            _ => None,
        }
}

If I change the downcast line to the following, it compiles, but the downcast never succeeds. I imagine it’s for the same reason, that LibVal is somehow not being seen as Any.

Any::downcast_ref::<Arc<T>>(&*lvref)

The full source file is here:

If it helps, the calling location where I’m creating the LibVal object and then trying to downcast is here:

Thanks, Rust is great and any suggestions are appreciated!


#2

Try using mopa. You just mopafy! your trait and you should be able to downcast it then.


#3

I think this has been a longstanding issue. The current best solution seems to be this. Relevant links:


#4

I tried using mopa really quick and it seems to work as expected. It compiles and runs with making the runtime cast the way it should. Thanks!