知识卡片
用插值拼接字段列表
quote! 能把若干输出片段装进同一段 Rust 语法。先把字段名和类型分别绑定给局部变量 name、ty,在 quote! { pub #name: #ty } 中用 # 插进各自的 token。写 #f.ident 只插入整个 f,余下的点号与 ident 会原样进入输出。
若 builder_fields 是逐字段生成片段的迭代器,写 #(#builder_fields,)* 就会逐片插值,并为每个片段附上逗号,包括可能存在的尾逗号。空迭代产生空列表。只写 #builder_fields 会要求把整个迭代器当成一个可输出值,书中 Map 因未实现 ToTokens 而报错。可直接把迭代器用于重复,或在需要简化函数签名时收集为向量。
相关卡片 [[用字段模型委托输出]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Making fields public with attribute macros 取命名字段并拼成输出 · 查看原书依据
Now all we have to do is add the map of streams to the struct that we are returning. And we need to tell Rust that these streams will be separated by a comma, or Rust will complain about syntax. quote offers a convenience for this, which looks quite similar to how you would handle multiple elements in a declarative macro: #(#name-of-your-variable,)* (i.e., take this variable, which contains zero or