Converting to a Box<Any>

百般思念 提交于 2021-02-07 20:16:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26595505/converting-to-a-boxany

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!