【发布时间】:2016-11-28 17:26:03
【问题描述】:
我正在尝试实现一个列表zipper。到目前为止,我有:
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ListZipper {
pub focus: Option<Tile>,
pub left: VecDeque<Tile>,
pub right: VecDeque<Tile>,
}
impl PartialEq for ListZipper {
fn eq(&self, other: &ListZipper) -> bool {
self.left == other.left && self.focus == other.focus && self.right == other.right
}
}
我现在正在尝试实现一个迭代器
impl Iterator for ListZipper {
type Item = Tile;
fn next(&mut self) -> Option<Tile> {
self.left.iter().chain(self.focus.iter()).chain(self.right.iter()).next().map(|w| *w)
}
}
在我看来这是有道理的。当迭代ListZipper 时,我想迭代left,然后是focus,然后是right。所以我链接这些迭代器并返回next()。
如果ListZipper 中的所有字段都为空,这将正常工作。只要一个不是空的,迭代ListZipper 就会导致无限循环。
问题不在于链条。如果我将其替换为例如self.left.iter(),和left不为空,问题是一样的。 focus 和 right 也是如此。
我尝试打印迭代器中的所有元素,它似乎从前到后通过VecDeque,然后卡住了。 IE。 next() 到达后面时光标不前进。
为什么?
我意识到我可能不希望 ListZipper 本身成为迭代器,但这是另一个讨论。
【问题讨论】:
-
您确实意识到
next每次调用时都会创建一个全新的迭代器,对吗?