unegare
unegare

Reputation: 2579

How to skip enum name passing its variant to a macro?

I would like not to mention each time the enumname which contains the variant supposing it's always the same. Is it possible?

the key thing there is in a struct variant in the enum.

on a more mundane level:

I've tried the following:

enum Types {
  t1,
  t2{id: u64}
}

macro_rules! createenum {
  (enum $enumname: ident { $( $variant: ident ( $arg1: literal, $arg2: expr ) ,)* } ) => {
    enum $enumname {
      $( $variant, )*
    }

    impl $enumname {
      fn arg2(&self) -> Option<Types> {
        match self {
          $( $enumname::$variant => Some(Types::$arg2), )*
          _ => None
        }
      }
    }

  }
}

createenum! {
  enum MyEnum {
    Var1("one", t1),
    Var2("two", t2{id: 5}),
  }
}

Evidently the code above does not work, since rust does not know what the t1 and t2 are. But I am loath to type the base enum each time.

How should I go about it?

Upvotes: 1

Views: 188

Answers (1)

Solomon Ucko
Solomon Ucko

Reputation: 6109

use Types::*; Rust Playground demo

Upvotes: 1

Related Questions