使用宏,如何获取结构字段的唯一名称? [英] Using macros, how to get unique names for struct fields?
问题描述
假设我这样调用了一些宏:
Suppose I have some macro invoked as such:
my_macro!(Blah, (a, b, c));
它会输出如下内容:
struct Blah {
a: i32,
b: i32,
c: i32
}
impl Blah {
fn foo() -> i32 {
a + b + c
}
}
(人工示例)
这些字段对结构是私有的,但是我需要允许重新定义.因此,输入
These fields will be private to the struct, but I need to allow redefinitions. So, the input
my_macro!(Blah, (a, b, c, a));
将生成类似以下内容的
struct Blah {
a1: i32,
b: i32,
c: i32,
a2: i32
}
impl Blah {
fn foo() -> i32 {
a1 + b + c + a2
}
}
命名方案不需要遵循任何逻辑模式.
The naming scheme doesn't need to follow any logical pattern.
这可能吗?
推荐答案
如果不使用编译器插件,不,我认为这是不可能的.两个原因:
Without using a compiler plugin, no, I don't believe this is possible. Two reasons:
-
您不能构造标识符.有
concat_idents!
,但是由于扩展宏的方式,在这种情况下它没有用.
You can't construct identifiers. There's
concat_idents!
, but due to the way macros are expanded, it's useless in this situation.
您不能进行非文字比较.也就是说,无法通过宏解决以前已经在a
中看到过一次的问题.
You can't do non-literal comparisons. That is, there's no way of the macro working out that it's already seen a
once before.
关于获得的最接近的结果是完全替换所有提供的标识符,并使用固定的标识符列表,但这可能不是您想要的;在这种情况下,只需要指定4个字段并生成固定大小的数组[i32; 4]
会更容易.
About the closest you could get is to just outright replace all the provided identifiers with a fixed list of identifiers, but that's probably not what you want; in that case, it'd be easier to just specify that you want 4 fields, and generate a fixed-size array [i32; 4]
.
这篇关于使用宏,如何获取结构字段的唯一名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!