由于SipHasher对我的用例来说太慢了,我试图实现自定义哈希函数。我发现an example用作基础来编译所有内容。
我目前的代码如下:
use std::collections::hash_state::{DefaultState};
use std::collections::{HashMap, HashSet};
use std::default::Default;
use std::hash::{Hash, Hasher, SipHasher};
use std::marker;
pub struct FnvHasher(u64);
impl Default for FnvHasher {
fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) }
}
impl Hasher for FnvHasher {
fn write(&mut self, bytes: &[u8]) {
let FnvHasher(mut hash) = *self;
for byte in bytes {
hash = hash ^ (*byte as u64);
hash = hash * 0x100000001b3;
}
*self = FnvHasher(hash);
}
fn finish(&self) -> u64 { self.0 }
}
fn main() {
let mut set:HashSet<i64, DefaultState<FnvHasher>> = HashSet::with_hash_state(DefaultState::<FnvHasher>);
}
编译时,我收到以下错误消息:
$ rustc -V
rustc 1.0.0-nightly (522d09dfe 2015-02-19) (built 2015-02-19)
$ rustc hash.rs
hash.rs:26:86: 26:111 error: mismatched types:
expected `std::collections::hash::state::DefaultState<FnvHasher>`,
found `fn(core::marker::PhantomData<FnvHasher>) -> std::collections::hash::state::DefaultState<FnvHasher> {std::collections::hash::state::DefaultState}`
(expected struct `std::collections::hash::state::DefaultState`,
found fn item) [E0308]
hash.rs:26 let mut set:HashSet<i64, DefaultState<FnvHasher>> = HashSet::with_hash_state(DefaultState::<FnvHasher>);
^~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
如何让上面的例子在HashSet / HashMap中编译或使用自定义哈希函数?
答案 0 :(得分:3)
查看DefaultState
:
pub struct DefaultState<H>(marker::PhantomData<H>);
你正好像以前那样对待它:
pub struct DefaultState<H>;
这种变化是最近的;现在必须明确使用通用参数。
为此,您现在必须使用Default::default()
,因为该字段是私有的,因此无法写入文字表达式。因此,DefaultState::<FnvHasher>
变为Default::default()
。
一旦你使用Default::default()
,你就可以全力以赴,用HashSet::with_hash_state(Default::default())
取代Default::default()
:
let mut set: HashSet<i64, DefaultState<FnvHasher>> = Default::default();
答案 1 :(得分:3)