此代码
use std::any::Any;
use std::collections::HashMap;
fn main() {
let x: HashMap<*const Any, i32> = HashMap::new();
}
给我以下错误:
error: the trait `core::marker::Sized` is not implemented for the type `core::any::Any` [E0277]
let x: HashMap<*const Any, i32> = HashMap::new();
^~~~~~~~~~~~
首先,当密钥类型为core::any::Any
时,我不明白它为什么抱怨*const core::any::Any
。不管*const _
是否use std::any::Any;
use std::mem::size_of;
fn main() {
println!("size_of(*const Any) = {}", size_of::<*const Any>());
}
的大小,无论它指向什么?为了测试这个,我尝试了:
size_of(*const Any) = 16
正如预期的那样,产生:
/missing
答案 0 :(得分:1)
这不是最漂亮的解决方案,但这是我想出的:
use std::any::Any;
use std::collections::HashMap;
use std::hash::{Hasher, Hash};
use std::cmp;
struct Wrapper {
v: *const Any,
}
impl Wrapper {
fn get_addr(&self) -> usize {
self.v as *const usize as usize
}
}
impl Hash for Wrapper {
fn hash<H: Hasher>(&self, state: &mut H) {
self.get_addr().hash(state)
}
}
impl cmp::PartialEq for Wrapper {
fn eq(&self, other: &Self) -> bool {
self.get_addr() == other.get_addr()
}
}
impl cmp::Eq for Wrapper {}
fn main() {
let x: HashMap<Wrapper, i32> = HashMap::new();
}