2

I have the following enum:

enum Token {
    Word(String),
    Semicolon,
    Comma
}

I do not implement Eq. I want to write a function to match the above through type comparisons:

fn expect(t: &Token, const_t: &Token) -> bool {
    match (t, const_t) {
        (&Token::Semicolon, &Token::Semicolon) => true,
        (&Token::Comma, &Token::Comma) => true,
        _ => false,
    }
}

The above code is working, but has poor scalablity. If I have 100 variants, I will have a lot of helper functions and will rely on the default match _ a lot.

I don't see an easy way to hide the different variants of the Enum to simply say "I want to match up the variants of two similar enums".

Are there any other workaround for this purpose?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Earth Engine
  • 10,048
  • 5
  • 48
  • 78
  • 2
    Why are you not comparing `&Token::Word`? Should two `Word` be marked "equal" even if their content is not? – Matthieu M. Jul 14 '17 at 13:48
  • 6
    Seems likely a duplicate of https://stackoverflow.com/q/32554285/155423 – Shepmaster Jul 14 '17 at 13:48
  • 1
    "I do not implement `Eq`." Uh... why? – DK. Jul 14 '17 at 13:53
  • @Shepmaster No... and yes I don't care the value as well, but I have already put an answer for that question. My question is further: how can I reduce the code I have to write as I only need to say "I want to match that both side of the tuple are in the SAME variant, but I don't want to say All those variant's names" – Earth Engine Jul 14 '17 at 13:54
  • @DK to make it more generic. Sometimes we don't want to have `Eq` and maybe the `Eq` is not what we want. – Earth Engine Jul 14 '17 at 13:55
  • 5
    @EarthEngine did you read the *entire* answer? Including the part that is "here's a macro to automatically generate the match function based on the enum definition"? – Shepmaster Jul 14 '17 at 13:56

0 Answers0