Reputation: 48248
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
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