知识卡片
同名函数封装条件生成
用 feature 切换生成内容时,可以保持调用方始终使用同一个帮助函数。附录为 generate_from_method 写两个同签名实现,启用 from 时产生 From 实现,关闭时产生空 token。互补的 cfg 谓词确保实际只编译其中一个实现,最终代码生成器始终将该函数返回的流拼入输出。
这里的 feature 增加了整个 crate 在相关展开中生成转换实现的能力。若同一 crate 中的两处调用需要分别选择是否生成,更合适的作用域是调用参数。
相关卡片 [[按调用控制代码生成]]、[[特性应叠加功能]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Exercise solutions 第 10 章练习:多属性与正向 feature · 查看原书依据
In struct_output.rs, we add one generate_from_method that will be compiled when the feature is active and one that returns an empty token stream when it is not: #[cfg(not(feature = "from"))].
参考来源
- 位置:《Write Powerful Rust Macros》附录 A《Exercise solutions》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/appendix-a.xhtml#p183)
- 结论依据:原文描述两种条件编译函数的输出,以及 generate_annotation_struct 如何无条件调用它并插入结果。
- 原始内容:In struct_output.rs, we add one generate_from_method that will be compiled when the feature is active and one that returns an empty token stream when it is not: #[cfg(not(feature = "from"))].