So the thing is, I’m using macros to implement Add trait on my mStruct.
I tried to implement this trait on both mStruct and &mStruct, and they both returns mStruct. However, within each macro, I have a line that need to be different, otherwise it won’t compile.
struct mStruct {
// Variables
}
macro_rules! implement_add {
($type:ty, $output:ty, $is_ref_mode:literal) => {
impl Add for $type {
type Output = $output;
fn add(self, rhs: Self) -> Self::Output {
if $is_ref_mode {
// Thing that don't compile if $is_ref_mode is false
} else {
// Thing that don't compile if $is_ref_mode is true
}
}
}
};
}
implement_add!(mStruct, mStruct, false);
implement_add!(&mStruct, mStruct, true);
Can I do this with a macro, or should I write the same function twice and change this line by hand?
>Solution :
Split your macro that it has two arms. Something like this:
struct mStruct {
// Variables
}
macro_rules! implement_add {
($type:ty, noref) => {
impl Add for $type {
type Output = $type;
fn add(self, rhs: Self) -> Self::Output {
// self should be Self
}
}
};
($type:ty, doref) => {
// note here & before $type
impl Add for &$type {
type Output = $type;
fn add(self, rhs: Self) -> Self::Output {
// self should be &Self
}
}
};
}
implement_add!(mStruct, noref);
implement_add!(mStruct, doref);