您如何在Rust的编译时间动态生成结构?
我有以下内容:
struct Health {
health: f32,
}
struct Position {
position: Vec2,
}
struct Collections {
healths: Vec<Health>,
positions: Vec<Position>,
}
我想自动生成collections
struct struct;我在想使用宏?
我认为也许我可以用自定义属性标记要包含的每个结构,然后具有构建collections
struct的宏。
我该怎么做?
I have the following:
struct Health {
health: f32,
}
struct Position {
position: Vec2,
}
struct Collections {
healths: Vec<Health>,
positions: Vec<Position>,
}
I would like to generate the Collections
struct automatically; I am thinking using a macro?
I thought perhaps I could mark each struct I want to include with a custom attribute and then have a macro which builds the Collections
struct.
How could I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了能够执行诸如自定义属性之类的事情,您需要编写
proc_macro
,它几乎可以用代码来完成您需要的任何事情。对于更简单的解决方案,您可以尝试使用普通的
macro_rules
。为此,您需要将您的类型定义包装到进行解析的宏中,并返回类型定义加上所需的额外代码,在您的情况下,container
类。类似的事情:
现在您可以使用宏来构建原始代码( Playground ):
请注意,作为书面的
#[Collection = XXX]
属性是强制性的,并且必须是每个结构定义中的第一个。To be able to do something like custom attributes you need to write a
proc_macro
, that can do almost anything you need with your code.For a simpler solution you may try with a normal
macro_rules
. For that you will need to enclose your type definitions into a macro that does the parsing, and emits back the type definition plus the extra code you need, in your case theContainer
class.Something like this:
Now you can use the macro to build your original code (playground):
Note that as written the
#[collection=xxx]
attribute is mandatory and must be the first in every struct definition.因此,我设法使用proc_macro解决了这个问题。将包含在最终
存储
struct中的每个结构都用组件
衍生属性标记。然后,使用存储
结构将使用storege!()
宏构建。So I managed to solve this problem using a proc_macro. Each struct which is to be included in the final
Storage
struct is marked with theComponent
derive attribute. TheStorage
struct is then built with thestorage!()
macro.