[英]Can't downcast from &mut Box<dyn Trait> as &mut dyn Any?
I encountered this issue, and I'm wondering why it doesn't work.我遇到了这个问题,我想知道为什么它不起作用。 I managed to replicate the problem:我设法复制了这个问题:
I'm trying to get back to the struct from &mut Box<dyn Trait>
, and this is my go at it:我试图从&mut Box<dyn Trait>
回到结构,这是我的 go :
use std::any::Any;
trait A {}
struct B;
impl A for B {}
fn main() {
let mut a: Box<dyn A> = Box::new(B);
let a_ref: &mut Box<dyn A> = &mut a;
match (a_ref as &mut dyn Any).downcast_mut::<B>() { // downcast here
Some(_b) => println!("found b"),
None => println!("found nothing")
}
}
But this does not find the struct behind it?但这并没有找到它背后的struct? Am I missing something?我错过了什么吗?
Here is a link to the playground这是游乐场的链接
I've tried to downcast to other things, such as Box<B>
or &mut B
but none if this works.我试图降低其他东西,例如Box<B>
或&mut B
但如果这有效,则没有。
You can't just say my_trait_object as &dyn Any
and expect to be able to downcast to the original type.您不能只my_trait_object as &dyn Any
并期望能够向下转换为原始类型。 It does not work by magic, you need the original type to coerce itself as dyn Any
, that's the only way it works.它不能通过魔法起作用,您需要将原始类型强制为dyn Any
,这是它起作用的唯一方式。 That is why the solutions here need to pass through the trait object, to get at the original type, to get it as an Any
: How to get a reference to a concrete type from a trait object?这就是为什么这里的解决方案需要通过特征 object,以获取原始类型,将其作为Any
:如何从特征 object 中获取对具体类型的引用?
What happens here is that a concrete type is coerced into a dyn Any
, but that concrete type is Box<dyn A>
.这里发生的情况是,具体类型被强制转换为dyn Any
,但具体类型是Box<dyn A>
。 This code prints "found box":此代码打印“找到的框”:
use std::any::Any;
trait A {}
struct B;
impl A for B {}
fn main() {
let mut a: Box<dyn A> = Box::new(B);
let a_ref: &mut Box<dyn A> = &mut a;
match (a_ref as &mut dyn Any).downcast_mut::<Box<dyn A>>() {
Some(_) => println!("found box"),
None => println!("found nothing"),
}
}
There's more explanation in the linked answers that I encourage you to read.我鼓励您阅读链接答案中的更多解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.