官术网_书友最值得收藏!

Examining the log

Looking at the list without consuming it is an iterator's job (see the info box), which—in Rust as well as in most other languages—is a simple implementation of an interface or trait. In fact, this is so common that the Rust docs have a great article (https://doc.rust-lang.org/std/iter/index.html#implementing-iterator), which is exactly what's required.

Since we are already working with heap references, the iterator can simply save an optional reference to a node and it's easy to move it forward and backward:

pub struct ListIterator {
current: Link,
}

impl ListIterator {
fn new(start_at: Link) -> ListIterator {
ListIterator {
current: start_at,
}
}
}

As the documentation states, a for loop uses two traits: Iterator and IntoIterator. Implementing the former is usually a good idea, as it provides access to the powerful methods in Iterator, such as map, fold, and so on, and nicely chains together with other—compatible—iterators:

impl Iterator for ListIterator {
type Item = String;
fn next(&mut self) -> Option<String> {
let current = &self.current;
let mut result = None;
self.current = match current {
Some(ref current) => {
let current = current.borrow();
result = Some(current.value.clone());
current.next.clone()
},
None => None
};
result
}
}

This iterator is responsible for moving one direction: forward. How can we walk back too?

主站蜘蛛池模板: 广州市| 卢龙县| 牡丹江市| 清新县| 镇赉县| 西藏| 屯昌县| 开化县| 安康市| 洛阳市| 英吉沙县| 老河口市| 达日县| 金溪县| 黄平县| 和平区| 宁国市| 雷波县| 娱乐| 临汾市| 安龙县| 梧州市| 鲁甸县| 哈巴河县| 西平县| 沾益县| 巴中市| 湘阴县| 防城港市| 罗定市| 永定县| 黑山县| 宁晋县| 眉山市| 永福县| 涟水县| 柳江县| 襄城县| 石楼县| 镇安县| 齐齐哈尔市|