Aurélien Foucault
Aurélien Foucault

Reputation: 559

Use macro in match branch

I have a macro that abstract a variant of my enum :

struct Test(u64);

enum MyEnum {
  Variant1(Test)
}

macro_rules! MyEnumVariant {
   ["1"] => MyEnum::Variant1
}

I want to use in a match branch :


fn main() {
  let t = MyEnum::Variant1(Test(3));

  match t {
    MyEnumVariant!["1"](test) => println!("Value of test is: {}", test.0)
  }
}

This cause a compile error. I don't find any syntax that allow me to use my macro to replace the variant access in the match.

Here is a playground link to this little example with the compile error.

Do you have a syntax to allow macros to be used here ?

Upvotes: 1

Views: 258

Answers (1)

Kevin Reid
Kevin Reid

Reputation: 43922

Make the macro enclose the whole pattern you want to produce. This compiles:

macro_rules! MyEnumVariant {
    ["1" ( $p:pat )] => { MyEnum::Variant1($p) }
}
match t {
    MyEnumVariant!["1"(test)] => println!("Value of test is: {}", test.0)
}

Upvotes: 2

Related Questions