← 返回起始笔记位置

知识卡片

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

用泛型复用关键字解析

理解等级:中级

两个关键字对应同一种值类型时,可以把不同的关键字类型作为解析函数的泛型参数。例子里的 parse_number<T: Parse>(input, error_message) 先消费类型为 T 的关键字,再消费等号、解析整数并返回 u16。调用者可指定 ::<kw::mem> 或 ::<kw::time>,并提供各自的失败消息。

syn::custom_keyword! 生成的关键字类型都实现了 Parse,所以辅助函数能统一接收它们。用于解析名称的逻辑仍有自己的路径,名称值应按 Ident 解析。

相关卡片 [[自定义关键字驱动解析]]、[[字段类型限定合法输入]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第09章《Writing an infrastructure DSL》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-9.xhtml#p96) - 结论依据:原书解释了泛型约束的由来,并在清单 9.15 展示如何利用关键字类型复用解析路径。 - 原始内容:The most interesting thing about parse_number is that we made it generic over Parse. That’s necessary because we want to parse the memory and time keywords. And Parse is a trait implemented by custom keywords.