为什么没有找到dyn任何类型的downcast_ref方法?

问题描述 投票:4回答:1

我正在尝试创建自己的模拟框架,我遇到了这个问题。当我试图降低我的Any类型,它没有找到downcast_ref方法:

use std::any::Any;
use std::collections::HashMap;

struct X;
struct Y;

fn main() {
    let mut map: HashMap<&'static str, Box<Any + Sync>> = HashMap::new();
    map.insert("x", Box::new(X));
    map.insert("y", Box::new(Y));

    get_x(map);
}

fn get_x(map: HashMap<&'static str, Box<Any + Sync>>) {
    let ref any = map["x"];
    let res = Any::downcast_ref::<X>(any); // Works
    let res = any.downcast_ref::<X>();     // Fails
}

Playground

error[E0599]: no method named `downcast_ref` found for type `&std::boxed::Box<(dyn std::any::Any + std::marker::Sync + 'static)>` in the current scope
  --> src/main.rs:18:19
   |
18 |     let res = any.downcast_ref::<X>();
   |                   ^^^^^^^^^^^^

如果我使用相关的函数语法调用它,它会找到该函数并且没有问题。

为什么编译器不能从downcast_ref()变量any中找到dyn Any方法?

casting rust
1个回答
1
投票

那是因为Any::downcast_ref()没有为dyn Any + 'static + Sync实现,仅用于:

  • dyn Any + 'static
  • dyn Any + 'static + Send
  • dyn Any + 'static + Send + Sync
© www.soinside.com 2019 - 2024. All rights reserved.