I have an enum with the following structure:
enum Expression {
Add(Add),
Mul(Mul),
Var(Var),
Coeff(Coeff)
}
where the 'members' of each variant are structs.
Now I want to compare if two enums have the same variant. So if I have
let a = Expression::Add({something});
let b = Expression::Add({somethingelse});
cmpvariant(a, b)
should be true
. I can imagine a simple double match
code that goes through all the options for both enum instances. However, I am looking for a fancier solution, if it exists. If not, is there overhead for the double match? I imagine that internally I am just comparing two ints (ideally).
As of Rust 1.21.0, you can use
std::mem::discriminant
:This is nice because it can be very generic:
Before Rust 1.21.0, I'd match on the tuple of both arguments and ignore the contents of the tuple with
_
or..
:I took the liberty of renaming the function though, as the components of enums are called variants, and really you are testing to see if they are equal, not comparing them (which is usually used for ordering / sorting).
For performance, let's look at the LLVM IR in generated by Rust 1.16.0 in release mode. The Rust Playground can show you this easily:
The short version is that we do a switch on one enum variant, then compare to the other enum variant. It's overall pretty efficient, but I am surprised that it doesn't just directly compare the variant numbers. Perhaps this is something that an optimization pass could take care of?
If you wanted to have a macro to generate the function, something like this might be good start.
The macro does have limitations though - all the variants need to have a single variant. Supporting unit variants, variants with more than one type, struct variants, visibility, etc are all real hard. Perhaps a procedural macro would make it a bit easier.