Macro to fill all variants?

You kind of need a macro to generate the required macro (a meta-macro of sorts). This makes the following code work:

derive_match! { matching_Fruit in [crate],
    enum Fruit {
        Apple(String),
        Cherry(u32)
    }
}

fn main ()
{
    let apple = Fruit::Apple("delicious".to_string());
    let cherry = Fruit::Cherry(42);

    matching_Fruit! {
        let Fruit(ref inner_contents) = apple;
        println!("fruit has {}", inner_contents);
    }
    matching_Fruit! {
        let Fruit(ref inner_contents) = cherry;
        println!("fruit has {}", inner_contents);
    }
}

(Taken from this other post)


Note: declaration-site syntax could be made nicer with a proc_macro_derive, but I don't know how much would people be interested by it :man_shrugging:

1 Like