← 返回起始笔记位置

知识卡片

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

迭代器闭包捕获配置

理解等级:中级

如果 map 的转换读取外层参数,如每个字段都要读取 use_defaults,它就捕获了环境,原来的 fn(&Field) -> TokenStream 函数指针类型无法表示它。可直接收集到 Vec<TokenStream>。仍需惰性消费时,可返回 impl Iterator<Item = TokenStream> + '_,并用 move 把配置参数带入闭包。显式写 Box<dyn Fn(...)> 也能用,但会引入装箱和动态调用。

相关卡片 [[返回借用输入的迭代器]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Builder with attributes 默认值配置与生成闭包 · 查看原书依据

      For our convenience, we are returning a Vec instead of a Map or impl. All three are valid inputs for quote, but Map now becomes a lot more annoying to use. As we are passing the use_defaults Boolean to map, this means that the function inside that map is now capturing a variable from its environment. That makes it a closure, which means our previous signature (Map<Iter<Field>, fn(&Field) TokenStream>) is invalid, as fn is a function pointer, not a closure.

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p79) - 结论依据:8.3 对比原来的函数指针、捕获 use_defaults 的闭包、装箱动态 Fn 和用 impl Iterator 或 Vec 返回的途径。 - 原始内容:For our convenience, we are returning a Vec instead of a Map or impl. All three are valid inputs for quote, but Map now becomes a lot more annoying to use. As we are passing the use_defaults Boolean to map, this means that the function inside that map is now capturing a variable from its environment. That makes it a closure, which means our previous signature (Map<Iter<Field>, fn(&Field) TokenStream>) is invalid, as fn is a function pointer, not a closure.