Error: the variable 'x' is still repeated at this depth

I am trying to write a macro in time, how long have the various functions performed.

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 produces a error: variable 'x' is still repeating at this depth.

In another statically typed language, I tried this in (F #) using closure - this was the easiest approach. Is it impossible to have such a common movie in Rust?

+4
source share
1 answer

The most immediate problem is that you ask the macro to analyze the sequence of one or more expressions when an extension can only deal with one. So just ask him.

-, , , , . , .

:

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
        }
    } 
}
+4

Source: https://habr.com/ru/post/1685018/


All Articles