Convert to box <Any>

I have it Box<Trait>

, and I want it to be attributed to Box<Obj>

. There is BoxAny to do this, but trying to call t.downcast::<Obj>()

says there is no method in scope downcast

.

The docs show you how to do this if you have a link. You can just do &Trait as &Any

. But it is boxedTrait as Box<Any>

not possible to do it.

Here's a playground showing what I mean.

+3


source to share


1 answer


Any

allows you to convert to a specific type, so you need to know that specific type when converting to Box<Any>

. However, you don't know the specific type if you only have a feature object for some other trait - this is exactly the point of feature objects. Therefore you cannot go from Box<SomeTrait>

to Box<Any>

, it is not possible.

Ideally it should be possible to write something like Box<Show+Any>

. This would allow for methods Show

as well as methods Any

. However, this is also not possible: you can write lifetime constraints and built-in types in addition to the main trait, so it Box<Show+Sync+'a>

is legal but Box<Show+Any>

not.

If you have a trait that you want to use with Any

, then the way to achieve this would be trait inheritance:



trait MyTrait : Any {
    // ...
}

      

However, inheritance does not work with trait objects, so you cannot call methods Any

on Box<MyTrait>

. There is a workaround for what the overriding involves Any

(as can be found here ), but it's nothing but pretty.

Unfortunately, I don't know of an easy way to do this. Perhaps something like this can be implemented with some unsafe code, but I don't know how.

+2


source







All Articles