Match enumerates of same struct with different generic

I have an enumerate goes like this:

pub enum Foo {
    Foo1(Foo1),
    Foo2(Foo2),
    Foo3(Foo3),
}

in which

pub type Foo1 = Bar<I1>;
pub type Foo2 = Bar<I2>;

in which

struct Bar<I>{
   var: I,
   ...
}

impl Bar{
   fn do(word: &str){
      ...
   }
}

here I am writing another function which needs a match block:

match something {
   Foo::Foo1(inner) => {
       inner.do(a_word)
   }
   Foo::Foo2(inner) => {
       inner.do(a_word)
   }
   _ => {
       (...)
   }
}

inner is of Bar struct, but different in Foo1 and Foo2:

inner for Foo1: Bar<I1>

inner for Foo2: Bar<I2>

The problem is, in the above block, the operation when something matches Foo1 and Foo2 is exact the same, but it is not very elegant to repeat the same operations twice.

I tried:

match something {
   Foo::Foo1(inner) | Foo::Foo2(inner)=> {
       inner.do(a_word)
   _ => {
       (...)
   }
}

It doesn't work, because the inner in Foo1 and Foo2 are of different types(as mentioned before)

So how can I match Foo1 and Foo2 compactly?

Thank you!

This will require macros:

derive_match!{
    matching_Foo in [crate],
    enum Foo {
        Foo1(Bar<u8>),
        Foo2(Bar<u32>),
    }
}

struct Bar<U> (U);

impl<U> Bar<U> {
    fn bar (self: &'_ Self, word: &'_ str)
    {}
}

fn foo (something: Foo) {
    let a_word = "A word";
    matching_Foo!{
        let FooN(inner) = something;
        inner.bar(a_word);
    }
}
1 Like

Wow thank you so much!

<off-topic>
This is oddly related, though humorous:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.