130. mem::discriminant — Compare Enum Variants, Ignore the Payload
You want to know “is this another Click?” — not whether the coordinates match. Hand-rolling a match for every variant gets old fast. std::mem::discriminant answers that question in one call.
The problem
Say you have an event enum with payload data on every variant:
| |
Two Clicks with different coordinates are still both clicks. Deriving PartialEq won’t help — that compares the inner data too. The usual workaround is a tedious match:
| |
Every new variant means another arm. Forget one and you’ve got a silent bug.
The fix: mem::discriminant
| |
discriminant(&value) returns an opaque Discriminant<T> representing which variant the value is — nothing more. Two Clicks with wildly different coordinates have the same discriminant; a Click and a KeyPress don’t.
No match, no missing-arm bugs, no recompile when you add a new variant.
Bonus: Discriminant<T> is Hash + Eq + Copy
That makes it a perfectly good HashMap key, which is great for counting events by variant without writing a tag enum:
| |
Reach for discriminant whenever you find yourself writing a kind() method or an “is this the same variant?” match. The std lib already has it.