我正在尝试创建自己的模拟框架,我遇到了这个问题。当我试图降低我的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
}
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
方法?
那是因为Any::downcast_ref()
没有为dyn Any + 'static + Sync
实现,仅用于:
dyn Any + 'static
dyn Any + 'static + Send
dyn Any + 'static + Send + Sync