1

Is it possible to write a macro that defines an enum which wraps an arbitrary number of (distinct) input types? I'd like to do a kind of type-level match.

type_switch!(i32 => println!("integer"), f32 => println!("float"), Foo => println!("foo"))

This would expand to:

{
    enum Wrapper {
        Variant1(i32),
        Variant2(f32),
        Variant3(Foo),
    }

    // impl From<i32>, From<f32>, From<Foo> for Wrapper

    |x: Wrapper| match x {
        Wrapper::Variant1(x) => println!("integer"),
        Wrapper::Variant2(x) => println!("float"),
        Wrapper::Variant3(x) => println!("foo"),
    }
}

so that I can write like

let switch = type_switch!(i32 => println!("integer"), f32 => println!("float"), Foo => println!("foo"));
switch(32.into()); // prints "integer"
switch(24.0.into()); // prints "float"
3
  • What do you expect wrapped(32.into()); to do or return?
    – Peter Hall
    Dec 9, 2018 at 18:34
  • Macros match on syntax not on runtime values. Probably you will need to define a trait that you can implement for each supported type. But then I'm not sure if you really need the macro.
    – Peter Hall
    Dec 9, 2018 at 18:45
  • The types that will be passed to switch are known and limited in my case, so I'd like to match those types exhaustively. On the other hand, I need several switches so I want to generalize the definition not to repeat myself.
    – pandaman
    Dec 9, 2018 at 18:58

2 Answers 2

1

Define a trait within your macro and implement it for each type:

macro_rules! type_switch {
    ($($ty: ty => $expr: expr),+) => {{
        trait TypeMatch {
            fn type_match(self);
        }
        $(
            impl TypeMatch for $ty {
                fn type_match(self) {
                    $expr
                }
            }
        )+
        TypeMatch::type_match
    }}
}

Notice that the first time you call the function the compiler will bind the type so that subsequent calls must be the same type:

struct Foo;

fn main() {
    let s = type_switch! {
        i32 => { println!("i32"); },
        f32 => { println!("f32"); },
        Foo => { println!("Foo"); }
    };

    s(0);
    s(Foo); // Error!
}

If you need to be able to call it with different types, this can be fixed (at a small cost) by using a trait object for dynamic dispatch:

macro_rules! type_switch {
    ($($ty: ty => $expr: expr),+) => {{
        trait TypeMatch {
            fn type_match(&self);
        }
        $(
            impl TypeMatch for $ty {
                fn type_match(&self) {
                    $expr
                }
            }
        )+
        |value: &dyn TypeMatch| {
            value.type_match()
        }
    }}
}

struct Foo;

fn main() {
    let s = type_switch! {
        i32 => { println!("i32"); },
        f32 => { println!("f32"); },
        Foo => { println!("Foo"); }
    };

    s(&0);
    s(&Foo);
}

Also notice that you have to pass references instead of values.

0
1

It can make sense to write wrapper types as you have proposed, but only if the type is needed in larger parts of your code.

Your specific example would define a new enum every time you use the macro, move the value into the new enum and then immediately throw it away.

That's not a idiomatic approach and if that is indeed your imagined use I'd recommend looking for different options.

That said, I have used wrapper types on a number of occasions.

Something like this will work for declaring a wrapper:

macro_rules! declare_wrapper {
  (
    $enum_name:ident {
      $( $variant_name:ident( $typ:ty : $description:expr ) ),*
    }
  )=> {
    pub enum $enum_name {
      $(
        $variant_name($typ),
      )*
    }

    $(
      impl From<$typ> for $enum_name {
        fn from(value: $typ) -> Self {
          $enum_name::$variant_name(value)
        }
      }
    )*

    impl $enum_name {
      fn describe(&self) -> &'static str {
        match self {
          $(
            &$enum_name::$variant_name(_) => $description,
          )*
        }
      }
    }
  };
}

declare_wrapper!( MyWrapper {
  MyInt(i64 : "int"),
  MyString(String : "string")
});

fn main() {
  let value = MyWrapper::from(22);
  println!("{}", value.describe());
}

You can also extend this to add additional methods or trait impls that you need. I've done similar things quite often.

4
  • Is it possible to remove variant names from the invocation of declare_wrapper? I'm not interested in the name so writing them is verbose.
    – pandaman
    Dec 9, 2018 at 19:25
  • No, variants need a name so you have to define one. PS: I added the From impl too.
    – theduke
    Dec 9, 2018 at 19:28
  • Hmm, I could omit variant names If I were able to generate a unique variant name for each type, but it seems not possible..
    – pandaman
    Dec 9, 2018 at 19:33
  • Sadly that can't be done in a macro. That would only be possible with the new proc macro system. There you could upper case the first character of the type and you would end up with variants like I32, etc, so no keywords are used. But that is much more complicated to implement and I don't think typing an extra word once in the definition is cumbersome.
    – theduke
    Dec 9, 2018 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.