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`)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With