Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

casting

rust

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?

like image 794
Akiner Alkan Avatar asked Nov 06 '22 18:11

Akiner Alkan


1 Answers

That is because Any::downcast_ref() is not implemented for dyn Any + 'static + Sync, only for:

  • dyn Any + 'static
  • dyn Any + 'static + Send
  • dyn Any + 'static + Send + Sync
like image 118
Stargateur Avatar answered Dec 08 '22 04:12

Stargateur