知识卡片
用字段模型委托输出
宏的入口可以只负责编排:从 AST 抽取 Field,逐个交给 StructField::new(&Field),再把自定义字段模型用于 quote! 的重复插值。模型保留名称和完整的 Type,由 quote::ToTokens::to_tokens(&self, tokens: &mut proc_macro2::TokenStream) 统一把 pub 名称: 类型 加入输出流。这样调用方无需在每次使用该模型时重写模板。
quote! 使用 proc_macro2::TokenStream,编译器的宏函数边界使用 proc_macro::TokenStream,可在返回处用 .into() 转换。显式在签名中使用 proc_macro2 时,把它声明为依赖。小型宏直接在 map 中组装通常更短,多处复用同一语义的解析类型与输出规则时,拆出自定义类型有助于明确职责。
相关卡片 [[用插值拼接字段列表]]、[[用解析特征定义输入语法]]。
结构图:
classDiagram
class Field {
+Option~Ident~ ident
+Type ty
}
class StructField {
+Ident name
+Type ty
+new(field: &Field) Self$
+to_tokens(&self, tokens: &mut TokenStream)
}
class ToTokens {
<<trait>>
+to_tokens(&self, tokens: &mut TokenStream)
}
class TokenStream {
<<proc_macro2>>
}
StructField ..> Field : 读取结构化语法
ToTokens <|.. StructField : 实现
ToTokens ..> TokenStream : 追加输出
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Making fields public with attribute macros 让字段模型负责输出 · 查看原书依据
This is more code—and complexity—than we had before, but there are positives as well. There is a separation of concerns: we have made a struct responsible for the retrieval and outputting of a field.
参考来源
- 位置:《Write Powerful Rust Macros》第04章《Making fields public with attribute macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-4.xhtml#p84)
- 结论依据:清单 4.11 给出构造、ToTokens 实现和迭代映射,第 4.6.1 节说明流类型及拆分产生的额外代码与复用收益。
- 原始内容:This is more code—and complexity—than we had before, but there are positives as well. There is a separation of concerns: we have made a struct responsible for the retrieval and outputting of a field.