知识卡片
生成代码使用完整路径
宏展开后的类型和函数名在调用方的程序中解析。书中若生成 Config(HashMap<String, String>),调用方没导入 HashMap 时就无法编译,若恰好存在同名结构体,还会解析到另一种类型。
书中把生成代码改成 std::collections::HashMap,省去调用方导入,并避免同名类型冲突。标准库路径还可按使用环境写成显式从根起始的形式。字段若公开,即使使用完整路径,也仍应将字段类型视作对外 API 的一部分。
相关卡片 [[编译期嵌入配置值]]、[[版本号承诺宏兼容性]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Macros and the outside world 解析路径、生成代码与名称解析 · 查看原书依据
This is something we have to avoid because the chance of a collision with the application code and library code grows with the size of both the project and our macro. So it’s good practice to always use full paths in generated code. Even when it comes to things included in Rust’s prelude (like std::vec::Vec), this may be worthwhile, because even these might not be available in certain environments or might be overridden by things declared in application code.
参考来源
- 位置:《Write Powerful Rust Macros》第10章《Macros and the outside world》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-10.xhtml#p45)
- 结论依据:原书分别用缺少导入和调用者自有同名 HashMap 演示同一问题,建议在生成代码中使用完整路径。
- 原始内容:This is something we have to avoid because the chance of a collision with the application code and library code grows with the size of both the project and our macro. So it’s good practice to always use full paths in generated code. Even when it comes to things included in Rust’s prelude (like std::vec::Vec), this may be worthwhile, because even these might not be available in certain environments or might be overridden by things declared in application code.