知识卡片
迭代器封装推进状态
Iterator 通过关联类型 Item 固定元素类型。next(&mut self) -> Option<Self::Item> 推进内部状态,Some 携带获得的项,None 表示没有项。调用者可用 for 消费序列,无需自己维护索引或结束条件。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 函数式语言特性:迭代器与闭包 Processing a Series of Items with Iterators · 查看原书依据
Notice that this definition uses some new syntax: type Item and Self::Item, which are defining an associated type with this trait. We’ll talk about associated types in depth in Chapter 19. For now, all you need to know is that this code says implementing the Iterator trait requires that you also define an Item type, and this Item type is used in the return type of the next method.
参考来源
- 位置:《The Rust Programming Language(第2版)》第13章 函数式语言特性:迭代器与闭包(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c13.xhtml`,块 0110)
- 结论依据:关联类型决定 `next` 返回的项类型,推进由实现管理。
- 原始内容:Notice that this definition uses some new syntax: type Item and Self::Item, which are defining an associated type with this trait. We’ll talk about associated types in depth in Chapter 19. For now, all you need to know is that this code says implementing the Iterator trait requires that you also define an Item type, and this Item type is used in the return type of the next method.