I have a struct that contains a unique id and uses that id for its hash:
use std::borrow::Borrow;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
type Id = u32;
#[derive(Debug, Eq)]
struct Foo {
id: Id,
other_data: u32,
}
impl PartialEq for Foo {
fn eq(&self, other: &Foo) -> bool {
self.id == other.id
}
}
impl Hash for Foo {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Borrow<Id> for Foo {
fn borrow(&self) -> &Id {
&self.id
}
}
I understand that I cannot modify the value of Foo::id
once I've put it into the HashSet
because that would change the hash. However, I would like to modify Foo::other_data
. I know I could remove it from the HashSet
, modify it, and insert it again, but a method like get_mut()
would be so much cleaner. Is there a way to accomplish something like this:
fn main() {
let mut baz = HashSet::new();
baz.insert(Foo {
id: 1,
other_data: 2,
});
if let Some(x) = baz.get_mut(&1) {
*x = 3;
}
}
Is this an anti-pattern; should I be using a HashMap
instead?