seanmonstar
seanmonstar

Reputation: 11444

Converting to a Box<Any>

I have a Box<Trait>, and want to be able to cast it to Box<Obj>. There is BoxAny to supposedly do this, but trying to call t.downcast::<Obj>() says there's not method downcast in scope.

The docs show how to do this if you have a reference. You can just do &Trait as &Any. But it doesn't seem to be possible to do boxedTrait as Box<Any>.

Here's a playground showing what I mean.

Upvotes: 4

Views: 1501

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 127721

Any allows downcasting to a concrete type, so you need to know this concrete type when you convert to Box<Any>. However, you don't know concrete type if you only have a trait object for some other trait - that's exactly the point of trait objects. So you can't go from Box<SomeTrait> to Box<Any>, it is impossible.

Ideally it should be possible to write something like Box<Show+Any>. This would allow using Show methods as well as Any methods. This is also impossible, however: you can only write lifetime bounds and built-in kinds in additional to the main trait, so Box<Show+Sync+'a> is legal, but Box<Show+Any> is not.

If you own the trait you want to use with Any, then a way to achieve this would be trait inheritance:

trait MyTrait : Any {
    // ...
}

However, inheritance does not work with trait objects, so you can't invoke Any methods on Box<MyTrait>. There is a workaround for that which involves reimplementing Any (as can be found here), but it is anything but pretty.

Unfortunately, I'm not aware of a simple way to do this kind of thing. Something like this is likely possible to implement with some unsafe code, probably, but I don't know how.

Upvotes: 1

Related Questions