5

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
  • 388,571
  • 95
  • 1,107
  • 1,366
vbezhenar
  • 11,148
  • 9
  • 49
  • 63

1 Answers1

7

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
  • 28,729
  • 6
  • 82
  • 98
  • 1
    Looks like the RFC since went through and the feature was implemented as [`std::mem::discriminant`](https://doc.rust-lang.org/std/mem/fn.discriminant.html) – ejoubaud Oct 25 '22 at 08:10