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

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?

主站蜘蛛池模板: 新建县| 社会| 库车县| 台山市| 钟祥市| 鹰潭市| 沁阳市| 湖北省| 乾安县| 迁安市| 伊宁县| 沐川县| 武宁县| 体育| 阜阳市| 水富县| 台中市| 安多县| 泽普县| 巴南区| 美姑县| 哈尔滨市| 赤壁市| 临泽县| 赤峰市| 辉南县| 罗源县| 靖西县| 武定县| 建始县| 云梦县| 杨浦区| 监利县| 松桃| 连城县| 沙坪坝区| 临清市| 班玛县| 沙洋县| 灌阳县| 华安县|