如何编写自定义派生宏?

问题描述 投票:0回答:1

我正在尝试在Rust中编写自己的派生模式宏,并且在其中的documentation在示例中有些缺乏。

我有一个像这样的结构:

#[derive(MyMacroHere)]
struct Example {
    id: i64,
    value: Option<String>,
}

我希望我的宏生成一个方法àla

fn set_fields(&mut self, id: i64, value: Option<String>) {
    // ...
}

使用TokenStream特性实现类似的基本步骤是什么?

rust rust-macros
1个回答
3
投票
  1. 为您的过程宏创建一个包: cargo new my_derive --lib
  2. 编辑Cargo.toml使其成为程序宏箱: [lib] proc-macro = true
  3. 实现你的程序宏: extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(MyMacroHere)] pub fn my_macro_here_derive(input: TokenStream) -> TokenStream { // ... }
  4. 导入过程宏并使用它: extern crate my_derive; use my_derive::MyMacroHere; #[derive(MyMacroHere)] struct Example { id: i64, value: Option<String>, }

困难的部分在于宏的实现。大多数人使用synquote包来解析传入的Rust代码,然后生成新代码。

例如,syn的文档以an example of a custom derive开头。您将解析结构(或枚举或联合),然后处理定义结构(单元,元组,命名字段)的各种方法。您将收集所需的信息(类型,可能是名称),然后您将生成相应的代码。

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.