Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: variable 'x' is still repeating at this depth

Tags:

macros

rust

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?

like image 854
wegry Avatar asked Sep 04 '17 11:09

wegry


1 Answers

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
        }
    } 
}
like image 129
DK. Avatar answered Oct 23 '22 20:10

DK.