我正在尝试创建自己的模拟框架,但遇到了问题。 当我尝试将我的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>();
| ^^^^^^^^^^^^
如果我使用关联函数语法调用它,它能找到函数并正常工作。
为什么编译器无法从类型为 dyn Any 的变量 any 中找到 downcast_ref() 方法?
dyn Any + 'static + Sync
可以自动转换为dyn Any + 'static
,因为函数式调用是有效的。 - Matthieu M.的impl。似乎存在一个“子类型”关系的限制,阻止从
Any + Sync中剥离
Sync以考虑只在
Any`上实现。这似乎更多是一种实现限制而不是基本类型系统限制。 - Matthieu M.