简体   繁体   English

转换为盒子<Any>

[英]Converting to a Box<Any>

I have a Box<Trait> , and want to be able to cast it to Box<Obj> . 我有一个Box<Trait> ,并希望能够将它投射到Box<Obj> There is BoxAny to supposedly do this, but trying to call t.downcast::<Obj>() says there's not method downcast in scope. BoxAny到按说这样做,但试图调用t.downcast::<Obj>()说,有没有方法downcast的范围。

The docs show how to do this if you have a reference. 如果您有参考,文档将显示如何执行此操作。 You can just do &Trait as &Any . 你可以&Trait as &Any But it doesn't seem to be possible to do boxedTrait as Box<Any> . 但似乎没有可能将boxedTrait as Box<Any>

Here's a playground showing what I mean. 这是一个展示我的意思的游乐场

Any allows downcasting to a concrete type, so you need to know this concrete type when you convert to Box<Any> . Any允许向下转换为具体类型,因此当您转换为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. 所以你不能从Box<SomeTrait>转到Box<Any> ,这是不可能的。

Ideally it should be possible to write something like Box<Show+Any> . 理想情况下,应该可以编写类似Box<Show+Any> This would allow using Show methods as well as Any methods. 这将允许使用Show方法以及Any方法。 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. 然而,这也是不可能的:除了主要特征之外,你只能编写生命界限和内置种类,因此Box<Show+Sync+'a>是合法的,但Box<Show+Any>不是。

If you own the trait you want to use with Any , then a way to achieve this would be trait inheritance: 如果您拥有要与Any一起使用的特征,那么实现这一目标的方法就是特征继承:

trait MyTrait : Any {
    // ...
}

However, inheritance does not work with trait objects, so you can't invoke Any methods on Box<MyTrait> . 但是,继承不适用于trait对象,因此您无法在Box<MyTrait>上调用Any方法。 There is a workaround for that which involves reimplementing Any (as can be found here ), but it is anything but pretty. 有一个解决方法,涉及重新实现Any这里可以找到),但它不是很漂亮。

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. 这样的事情很可能用一些不安全的代码来实现,但是我不知道怎么做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM