我有一个结构体,除其他数据外,还有一个独特的id
:
struct Foo {
id: u32,
other_data: u32,
}
我想使用id
作为键并将其保留在结构内部:
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
impl PartialEq for Foo {
fn eq(&self, other: &Foo) -> bool {
self.id == other.id
}
}
impl Eq for Foo {}
impl Hash for Foo {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
这有效:
pub fn bar() {
let mut baz: HashSet<Foo> = HashSet::new();
baz.insert(Foo {
id: 1,
other_data: 2,
});
let other_data = baz.get(&Foo {
id: 1,
other_data: 0,
}).unwrap()
.other_data;
println!("other_data: {}", other_data);
}
有什么办法可以写baz.get(1).unwrap().other_data;
代替baz.get(&Foo { id: 1, other_data: 0 }).unwrap().other_data;
?
另一种选择可能是HashMap
其中密钥包含在struct
。然而,我不能拥有id
结构内部和重复的id
用于key
.