知识卡片

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

返回借用输入的迭代器

理解等级:中级

当函数返回对字段集合进行惰性遍历的迭代器时,调用结束后迭代器还会读取输入。示例签名 fn builder_field_definitions(fields: &Punctuated<Field, Comma>) -> impl Iterator<Item = TokenStream2> + '_ 对外承诺能逐项产生令牌流,并把返回值的可用期关联到输入借用,调用者无需知道具体的 Map 类型。带多个借用输入时,显式命名生命周期可以说清关系。此处保留书中 Rust 2021 示例的写法。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Testing a builder macro 重构与内部测试成本 · 查看原书依据

      In one of the exercises, we had a very concrete return type for a function like builder_field_definitions: Map<Iter<Field>, fn(&Field) -> TokenStream>. That works, but this impl Iterator<Item = TokenStream2> + '_ is more idiomatic when you return iterator types. Instead of specifically telling Rust that the function gives back a Map, we say it is something that iterates over token streams: impl Iterator<Item = TokenStream2>. The '_ is obligatory, as Rust will tell you if you forget to add it.

    参考来源

    - 位置:《Write Powerful Rust Macros》第06章《Testing a builder macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-6.xhtml#p94) - 结论依据:清单 6.18 的迭代器借用了输入字段集合,说明文字比较 Map 具体类型与 impl Iterator 以及示例使用的生命周期界限。 - 原始内容:In one of the exercises, we had a very concrete return type for a function like builder_field_definitions: Map<Iter<Field>, fn(&Field) -> TokenStream>. That works, but this impl Iterator<Item = TokenStream2> + '_ is more idiomatic when you return iterator types. Instead of specifically telling Rust that the function gives back a Map, we say it is something that iterates over token streams: impl Iterator<Item = TokenStream2>. The '_ is obligatory, as Rust will tell you if you forget to add it.