ideasman42
ideasman42

Reputation: 48248

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

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`)

Upvotes: 3

Views: 859

Answers (1)

Havvy
Havvy

Reputation: 1511

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.

Upvotes: 5

Related Questions