这段代码
use std::any::Any;
use std::collections::HashMap;
fn main() {
let x: HashMap<*const Any, i32> = HashMap::new();
}
Run Code Online (Sandbox Code Playgroud)
给我以下错误:
error: the trait `core::marker::Sized` is not implemented for the type `core::any::Any` [E0277]
let x: HashMap<*const Any, i32> = HashMap::new();
^~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
首先,我不明白为什么它是抱怨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>());
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,产生:
size_of(*const Any) = 16
Run Code Online (Sandbox Code Playgroud)
这不是最漂亮的解决方案,但这是我想出的:
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();
}
Run Code Online (Sandbox Code Playgroud)