知识卡片

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

用特性控制宏的导出

理解等级:中级

Cargo feature 可以决定哪些宏入口及其依赖一起编进库。本章在宏 crate 的 Cargo.toml 声明 struct = [],再用 #[cfg(feature = "struct")] 保护 config_struct、其输出模块和专用导入。调用方启用该 feature 后才可导入属性宏,函数式配置宏有自己的启用策略。

默认 feature 可以提供开箱可用的宏。调用方用 default-features = false 加显式 features 请求自己需要的能力。真实项目还可以让 feature 激活可选依赖并重导出其过程宏,书中以 Serde 的 derive 与 Tokio 的 macros 为例。

相关卡片 [[同库复用多个过程宏]]、[[特性应叠加功能]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Macros and the outside world 用 feature 或参数控制功能 · 查看原书依据

      The entry point for our attribute macro is now annotated with #[cfg(feature = "struct")], meaning it will only be included when the struct feature is enabled. We can do the same for the DeriveInput import. More importantly, our new file/module struct_output is only imported when the feature is active. This is why we moved those functions to a separate file: it enables hiding all three in one go.

    参考来源

    - 位置:《Write Powerful Rust Macros》第10章《Macros and the outside world》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-10.xhtml#p63) - 结论依据:原文说明 feature 配置同时包围入口、专用导入与模块,后文给出 Serde 和 Tokio 的依赖映射。 - 原始内容:The entry point for our attribute macro is now annotated with #[cfg(feature = "struct")], meaning it will only be included when the struct feature is enabled. We can do the same for the DeriveInput import. More importantly, our new file/module struct_output is only imported when the feature is active. This is why we moved those functions to a separate file: it enables hiding all three in one go.