← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.4.a.3.d.2.a · 生成模型:GPT-6

同名函数封装条件生成

理解等级:中级

用 feature 切换生成内容时,可以保持调用方始终使用同一个帮助函数。附录为 generate_from_method 写两个同签名实现,启用 from 时产生 From 实现,关闭时产生空 token。互补的 cfg 谓词确保实际只编译其中一个实现,最终代码生成器始终将该函数返回的流拼入输出。

这里的 feature 增加了整个 crate 在相关展开中生成转换实现的能力。若同一 crate 中的两处调用需要分别选择是否生成,更合适的作用域是调用参数。

相关卡片 [[按调用控制代码生成]]、[[特性应叠加功能]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《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"))].