I'm trying to write a macro to time how long various functions are executing.
macro_rules! timer {
($( $x: expr ),+ ) => {
let now = SystemTime::now();
let val = $x;
match now.elapsed() {
Ok(elapsed) => {
// This should include a message at some point alongside the timing
println!("{}", elapsed.as_secs());
}
Err(e) => {
println!("{:?}", e);
}
}
val
}
}
but the compiler throws out a error: variable 'x' is still repeating at this depth
.
In another statically typed language I've tried this in (F#), using closures was the approach that was the simplest. Is it not possible to have a generic macro like this in Rust?
The most immediate problem is that you're asking the macro to parse a sequence of one or more expressions, when the expansion is only capable of dealing with one. So just ask for one.
Secondly, you want the expansion to result in an expression, but you've written it to expand to several statements. To fix that, expand to a block.
Fixing those gives:
macro_rules! timer {
($x: expr) => {
{
let now = SystemTime::now();
let val = $x;
match now.elapsed() {
Ok(elapsed) => {
// This should include a message at some point alongside the timing
println!("{}", elapsed.as_secs());
}
Err(e) => {
println!("{:?}", e);
}
}
val
}
}
}
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