知识卡片
编译期嵌入配置值
当配置在发布时已经确定,过程宏可以在编译时读取文件,把解析后的值生成为 Rust 字面量。书中的 config! 以扁平 YAML 为输入,读取默认路径或调用者通过 path = "..." 指定的文件,然后用 serde_yaml 将其读成 HashMap<String, String>。输出是 Config 及其 new,后者运行时用生成的插入语句重建映射。运行时变化需要重新生成这份代码。
可预期的文件打开或 YAML 解析失败应转换为 syn::Error,再发出编译错误 token。书中给文件打开错误补上路径及系统报错,使调用方可以直接定位文件。
相关卡片 [[嵌入字面量可用静态切片]]、[[同库复用多个过程宏]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Macros and the outside world 解析路径、生成代码与名称解析 · 查看原书依据
Start with lib.rs, which reads the token stream input using a struct from input.rs and produces output via a helper function. It also contains some of the core logic of our macro: finding and reading YAML.
参考来源
- 位置:《Write Powerful Rust Macros》第10章《Macros and the outside world》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-10.xhtml#p28)
- 结论依据:原文明示先读取文件、解析为字符串映射,再交给生成函数。清单 10.6–10.8 给出诊断及嵌入路径。
- 原始内容:Start with lib.rs, which reads the token stream input using a struct from input.rs and produces output via a helper function. It also contains some of the core logic of our macro: finding and reading YAML.