简体   繁体   中英

Why is the downcast_ref method not found for the dyn Any type?

I am trying to create my own mocking framework and I've bumped into this problem. When I try to downcast my Any type, it does not find the downcast_ref method:

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>();
   |                   ^^^^^^^^^^^^

If I call it using the associated function syntax, it finds the function and works with no problem.

Why can the compiler not find the downcast_ref() method from the variable any which is a dyn Any type?

这是因为未对dyn Any + 'static + Sync实施Any::downcast_ref() ,仅适用于:

  • dyn Any + 'static
  • dyn Any + 'static + Send
  • dyn Any + 'static + Send + Sync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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