首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rust无法从任何扩展的特征对象执行downcast_ref

Rust无法从任何扩展的特征对象执行downcast_ref
EN

Stack Overflow用户
提问于 2021-04-22 12:16:26
回答 1查看 128关注 0票数 2

Here is the Rust Playground of the example code.

代码语言:javascript
复制
use std::any::Any;

pub trait MemorizedOutput: Any {
    fn as_any(&self) -> &dyn Any;
}

impl<T: Any> MemorizedOutput for T {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

fn main() {
    let a = Box::new(1i32) as Box<dyn MemorizedOutput>;
    println!("{}", a.as_any().downcast_ref::<i32>().unwrap());
}

为什么上面的代码在unwrap()中会死机?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-22 12:25:13

Box<dyn MemorizedOutput>实现了Any,因此它包含在MemorizedOutput的全面实现中。根据https://doc.rust-lang.org/reference/expressions/method-call-expr.html,Rust将优先选择在Box<dyn MemorizedOutput>上实现的方法,而不是解引用的类型dyn MemorizedOutput。所以a.as_any()实际上是<Box<dyn MemorizedOutput> as MemorizedOutput>::as_any(&a),显然不能向下转换为i32

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67206692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档