知识卡片
用特性控制宏的导出
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.