4

I have an enum with some nested values. I want to check that this enum is of given variant but without specifying what's inside. Check the following program:

enum Test {
    Zero,
    One(u8),
    Two(u16),
    Four(u32),
}

fn check(x: Test, y: Test) -> bool {
    x == y;
}

fn main() {
    let x = Test::Two(10);
    let b1 = check(x, Test::One);
    let b2 = check(x, Test::Two);
    let b3 = match x {
        Test::Four(_) => true,
        _ => false,
    }   
}

b3 checks that x is Test::Four with an arbitrary value inside. I want that check to be done in the function check. Current code does not compile and I can't figure out how can I extract only enum variant without corresponding inside values.

I guess that could done with macro transforming to match expression, but is it possible to do that without macro?

I can see that Test::One is fn(u16) -> Test {Two}. Can I use that fact? To test that x was created using that function.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
vbezhenar
  • 9,757
  • 8
  • 44
  • 58

1 Answers1

6

This is not supported (yet). There is the active RFC 639 which suggests implementing a function that returns an integer which corresponds to the enum discriminant. With that hypothetical function you could expect the following to work:

assert_eq!(Test::Two(10).discriminant(), Test::Two(42).discriminant());
oli_obk
  • 25,579
  • 3
  • 73
  • 89