除非传入变量名,否则为什么不能访问在宏中声明的变量? [英] Why can I not access a variable declared in a macro unless I pass in the name of the variable?

查看:41
本文介绍了除非传入变量名,否则为什么不能访问在宏中声明的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个宏:

macro_rules! set_vars {
    ( $($x:ident),* ) => {
        let outer = 42;
        $( let $x = outer; )*
    }
}                                                                             

扩展此调用的范围:

set_vars!(x, y, z);

达到我的期望(来自-pretty = expanded ):

into what I expect (from --pretty=expanded):

let outer = 42;
let x = outer;
let y = outer;
let z = outer;

在随后的代码中,我可以打印 x y z 很好,但是 outer 似乎尚未定义:

In the subsequent code I can print x, y, and z just fine, but outer seems to be undefined:

error[E0425]: cannot find value `outer` in this scope
  --> src/main.rs:11:5
   |
11 |     outer;
   |     ^^^^^ not found in this scope

如果我将 outer 变量作为显式宏参数传递,则可以访问它.

I can access the outer variable if I pass it as an explicit macro parameter.

这是否是故意的,与宏观卫生"有关?如果是这样,那么以某种特殊方式在-pretty = expanded 中标记此类内部"变量可能有意义吗?

Is this intentional, something to do with "macro hygiene"? If so, then it would probably make sense to mark such "internal" variables in --pretty=expanded in some special way?

推荐答案

是的,这是宏观卫生.在宏内声明的标识符在宏外不可用(反之亦然).Rust宏不是C宏(也就是说,Rust宏不只是替换美化的文本).

Yes, this is macro hygiene. Identifiers declared within the macro are not available outside of the macro (and vice versa). Rust macros are not C macros (that is, Rust macros are more than glorified text replacement).

另请参阅:

这篇关于除非传入变量名,否则为什么不能访问在宏中声明的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆