macros - 错误 : variable 'x' is still repeating at this depth

标签 macros rust

我正在尝试编写一个宏来计算各种函数的执行时间。

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

但编译器抛出一个错误:变量 'x' is still repeating at this depth

在另一种静态类型语言中,我在 (F#) 中尝试过,使用闭包是最简单的方法。在 Rust 中不可能有像这样的通用宏吗?

最佳答案

最直接的问题是当扩展只能处理一个时,您要求宏解析一个或多个表达式的序列。所以只一个。

其次,您希望扩展产生一个表达式,但您已将其编写为扩展为多个语句。要解决这个问题,请扩展到一个 block 。

解决这些问题:

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

关于macros - 错误 : variable 'x' is still repeating at this depth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036038/

相关文章:

c++ - 取消定义和重新定义 __cplusplus 宏

与预处理器指令混淆

rust - Rust 中带有整数和 float 的泛型函数的问题。在 Rust 中研究计算机程序的结构和解释

rust - 使用 impl fmt::Display 将枚举转换为字符串

c - 将可变长度数组声明为宏

c - 宏和后增量

Rust tokio 无限循环用于多个按钮监听

rust - 可变借入带清理的两部分

c - 定义一个引入一对变量的宏

rust - 从其实现包装HashMap的特征中消除生命周期参数?