首页 > 解决方案 > 在 Rust“macro_rules”宏中的调用站点使用本地绑定

问题描述

考虑以下代码段:

macro_rules! quick_hello {
    ($to_print:expr) => {
        {
            let h = "hello";

            println!("{}", $to_print)
        }
    }
}

fn main() {
    quick_hello!(h);
}

如果我编译它,我会得到:

error[E0425]: cannot find value `h` in this scope
  --> src/main.rs:12:18
   |
12 |     quick_hello!(h);
   |                  ^ not found in this scope

但是不应该将quick_hello调用main扩展为包含该let h = "hello"语句的块,从而允许我在调用站点将其用作“hello”的速记吗?

我可能会知道这样做是为了保持宏的卫生,但是如果我需要上述行为怎么办?有没有办法“关闭”卫生来实现这一目标?

标签: rustmacroshygienerust-decl-macros

解决方案


处理quick_hellocallrustc正在寻找一个有效的表达式$to_print:expr。但h在该上下文中不是有效的表达式,因此rustc不会继续执行宏实现并打印错误。


推荐阅读