From 69a628df7270acde3cbd95daade9d278904c7d0b Mon Sep 17 00:00:00 2001 From: sunface Date: Wed, 16 Mar 2022 16:05:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E7=AB=A0=E8=8A=82=EF=BC=9A[d?= =?UTF-8?q?eque-=E8=BF=AD=E4=BB=A3=E5=99=A8]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/SUMMARY.md | 1 + src/too-many-lists/deque/iterator.md | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/too-many-lists/deque/iterator.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index b43507af..66539706 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -171,6 +171,7 @@ - [数据布局和基本操作](too-many-lists/deque/layout.md) - [Peek](too-many-lists/deque/peek.md) - [基本操作的对称镜像](too-many-lists/deque/symmetric.md) + - [迭代器](too-many-lists/deque/iterator.md) - [易混淆概念解析](confonding/intro.md) - [切片和切片引用](confonding/slice.md) - [Eq 和 PartialEq](confonding/eq.md) diff --git a/src/too-many-lists/deque/iterator.md b/src/too-many-lists/deque/iterator.md new file mode 100644 index 00000000..51967d55 --- /dev/null +++ b/src/too-many-lists/deque/iterator.md @@ -0,0 +1,26 @@ +# 迭代器 +坏男孩最令人头疼,而链表实现中,迭代器就是这样的坏男孩,所以我们放在最后来处理。 + +## IntoIter +由于是转移所有权,因此 `IntoIter` 一直都是最好实现的: +```rust +pub struct IntoIter(List); + +impl List { + pub fn into_iter(self) -> IntoIter { + IntoIter(self) + } +} + +impl Iterator for IntoIter { + type Item = T; + fn next(&mut self) -> Option { + self.0.pop_front() + } +} +``` + +但是关于双向链表,有一个有趣的事实,它不仅可以从前向后迭代,还能反过来。前面实现的是传统的从前到后,那问题来了,反过来该如何实现呢? + +答案是: `DoubleEndedIterator`,它继承自 `Iterator`( 通过 [`supertrait`](https://course.rs/basic/trait/advance-trait.html?highlight=supertrait#特征定义中的特征约束) ),因此意味着要实现该特征,首先需要实现 `Iterator`。 +