Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way change a single lign in a macro using a compile-time constant in Rust?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading