I have this enum:
enum MyEnum {
Var1,
Var2(u32),
Var3(u32, u32),
}
and I want to achieve the following behavior:
let mut set = HashSet::new();
set.insert(MyEnum::Var1);
set.insert(MyEnum::Var1);
set.insert(MyEnum::Var2(1));
set.insert(MyEnum::Var2(2));
set.insert(MyEnum::Var3(1, 1));
set.insert(MyEnum::Var3(1, 1));
set.insert(MyEnum::Var3(2, 1));
set.insert(MyEnum::Var3(2, 2));
println!("set = {:?}", set);
// set = {Var1, Var2(1), Var2(2), Var3(1, 1), Var3(2, 1)}
That is, I want to change the Hash
behavior for variant Var3
specifically to depend on its first u32
only.
Importantly, I don't want to exhaustively match
each enum variant since I want to retain the default behavior for all other enum variants. Hence, as far as I can tell, these answers are not sufficient for what I am looking for.
The solution I came up with is this:
#[derive(Debug, Eq)]
enum MyEnum {
Var1,
Var2(u32),
Var3(u32, u32),
}
impl PartialEq for MyEnum {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(MyEnum::Var3(a, _), MyEnum::Var3(b, _)) => a == b,
_ => format!("{:?}", self) == format!("{:?}", other),
}
}
}
impl Hash for MyEnum {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
MyEnum::Var3(a, _) => a.hash(state),
_ => format!("{:?}", self).hash(state)
}
}
}
... and I am looking for feedback/better solutions.