Since defining the matching macro is too WET for my taste, I have written a meta-macro to automagically derive such macro, resulting in the following code being correct:
derive_match!{matching_BinOp in [crate],
#[derive(Debug)]
pub
enum BinOp {
Add { left: i32, right: i32 },
Sub { left: i32, right: i32 },
}
}
impl BinOp {
fn left_eq_right (&self) -> bool
{
matching_BinOp! {
let Op { ref left, ref right } = *self;
left.eq(right)
}
}
}
#[derive(Debug)]
struct Struct {
name: String,
operation: BinOp,
}
fn main ()
{
let mut foo = Struct {
name: "Metamatician".into(),
operation: BinOp::OpAdd { left: 21, right: 21 },
};
dbg!(&foo);
assert!(foo.operation.left_eq_right());
foo.operation = BinOp::OpSub { left: 69, right: 27 };
dbg!(&foo);
assert!(::core::ops::Not::not(
foo.operation.left_eq_right()
));
}
where
impl BinOp {
fn left_eq_right (&self) -> bool
{
matching_BinOp! {
let Op { ref left, ref right } = *self;
left.eq(right)
}
}
}
expands to
impl BinOp {
fn left_eq_right (&self) -> bool
{
use crate::BinOp::*;
match *self {
OpAdd { ref left, ref right } => {
left.eq(right)
},
OpSub { ref left, ref right } => {
left.eq(right)
},
}
}
}
I am thinking about publishing the meta-macro in its own crate, although it will most probably get added to ::candy
. What do you think?