【发布时间】:2016-08-02 10:12:25
【问题描述】:
我正在尝试使用 HashSet<String> 作为其他 HashSet 的密钥。
我发现 this question and answer 指出要为 HashSet<String> 实现 Hash 特征,但我无法让我的具体案例起作用。
幸运的是,我的情况更受约束,所以我需要的是:
- 为
HashSet<String>类型实现hash特征only - 现在散列应该很简单:
集合{"q3", "q1", "q2"} 应该被散列为它的一个简单的有序连接字符串版本,类似于hash("q1-q2-q3")。获取"q1-q2-q3" 不是问题,但在hash 中使用它会引发我无法处理的各种错误。
这是我的实现尝试,但它不起作用。我认为 StateSet 包装器不是正确的做法,因为我丢失了所有重要的 HashSet 方法
use std::collections::{HashMap,HashSet};
use std::hash::{Hash,Hasher};
type State = String;
struct StateSet(HashSet<State>);
impl PartialEq for StateSet {
fn eq(&self, other: &StateSet) -> bool {
self.is_subset(&other) && other.is_subset(&self)
}
}
impl Eq for StateSet {}
impl Hash for StateSet {
fn hash<H>(&self, state: &mut H) where H: Hasher {
let a: Vec<State> = self.iter().collect();
a.sort();
for s in a.iter() {
s.hash(state);
}
}
}
fn main() {
let hmap: HashSet<StateSet> = HashSet::new();
}
【问题讨论】: