知识卡片
返回借用输入的迭代器
当函数返回对字段集合进行惰性遍历的迭代器时,调用结束后迭代器还会读取输入。示例签名 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.