我正在尝试在Rust中编写自己的派生模式宏,而documentation在示例中有点缺乏 .
我有一个像这样的结构:
#[derive(MyMacroHere)]
struct Example {
id: i64,
value: Option<String>,
}
我希望我的宏生成一个方法àla
fn set_fields(&mut self, id: i64, value: Option<String>) {
// ...
}
使用 TokenStream
特性实现类似的基本步骤是什么?
1 回答
困难的部分在于宏的实现 . 大多数人使用syn和quote包来解析传入的Rust代码,然后生成新代码 .
例如,syn的文档以an example of a custom derive开头 . 您将解析结构(或枚举或联合),然后处理定义结构(单元,元组,命名字段)的各种方法 . 您'll collect the information you need (type, maybe name), then you'将生成适当的代码 .
也可以看看:
Procedural Macros for Custom derive
Documentation for proc_macro
Documentation for syn
Documentation for quote
Is it possible to add your own derivable traits, or are these fixed by the compiler?