Compare equality of enums with associated values without match

#1

I am writing a simple scanner that retrieves tokens from a string slice. So, I have something like this,

enum TokenKind { Str(String) Num(i32), … };

I am trying to write a test case for the scanner. So, I am creating a vector of TokenKinds, and then my scanner retrieves another vector, and I am trying to compare them one-by-one.

In the loop, I have read-only references to both elements, and I don’t know of any less messy of comparing them. At this point, I am doing this,

match(kind_expected, kind_from_scanner) {
(Str(ref x), Str(ref y) => { assert_eq!(*x, *y); },

_ => panic!(“bad”);
}

So, I need to have this for each enum category, and is there any way to make it easier?

Daniel.

0 Likes

#2

If you can #[derive(PartialEq, Eq)] on your enum, you can use the equality operator. But that will just use the match internally.

0 Likes