Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use an argument multiple times in a Rust macros with a single instansiation?

Tags:

macros

rust

Is it possible to use an argument multiple times in a Rust macro, only having the argument instantiated once?

Take this simple example:

macro_rules! squared {
    ($x:expr) => {
        $x * $x
    }
}

While this works, if called like squared!(some_function() + 1), the function will be called multiple times. Is there a way to avoid this?

Non-working example:

macro_rules! squared {
    ($x:expr) => {
        let y = $x;
        y * y
    }
}

Gives a compile error:

 error: expected expression, found statement (`let`)
like image 455
ideasman42 Avatar asked Dec 06 '25 06:12

ideasman42


1 Answers

Yes, you're just missing an extra set of braces to contain the expression.

macro_rules! squared {
    ($x:expr) => {{
        let y = $x;
        y * y
    }}
}

Note that this macro will only work for expressions that have a type that implements Copy.

like image 159
2 revs, 2 users 53%Havvy Avatar answered Dec 08 '25 06:12

2 revs, 2 users 53%Havvy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!