10

I would like to pass in the parameters what arm of the enum I need to match, something like this:

enum D {
    A(i64),
    B(u64),
    C(u64, u64),
}
let a = D.A(10);
println!(a.is_of(D.A)); // true
println!(a.is_of(D.B)); // false

I know I can use matching rules for this, but I'd like this is_of method to take as an input of the enum options for my purposes.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
asosnovsky
  • 2,158
  • 3
  • 24
  • 41

2 Answers2

14

You cannot.

  • It is not possible to pass types as function parameters.
  • Enum variants are not types to start with.

If you are OK using a macro instead of a function, see

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 13
    Man.. I still don't know why enums cannot be passed as parameters in Rust. It's really counter-intuitive. – Matthew S Jul 09 '20 at 05:55
2

The discriminant of an enum variant can be passed for compairson

use std::mem::{discriminant,Discriminant};

enum MyEnum {
  A,
  B,
}

fn is_enum_variant(value: &MyEnum, d: Discriminant<MyEnum>) -> bool {
  discriminant(value) == d
}

fn main() {
  println!("Is variant: {}", is_enum_variant(&MyEnum::A, discriminant(&MyEnum::A)));
  println!("Is variant: {}", is_enum_variant(&MyEnum::A, discriminant(&MyEnum::B)));
}

Rust Playground

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567