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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With