I have a struct that has, among other data, a unique id
:
struct Foo {
id: u32,
other_data: u32,
}
I want to use the id
as the key and keep it inside of the struct:
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);
}
}
This works:
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);
}
Is there any way to write baz.get(1).unwrap().other_data;
instead of baz.get(&Foo { id: 1, other_data: 0 }).unwrap().other_data;
?
An alternative might be a HashMap
where the key is contained inside the struct
. However, I can't have the id
inside the struct and a duplicate id
used for the key
.