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

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?

主站蜘蛛池模板: 拉孜县| 富阳市| 齐齐哈尔市| 惠安县| 成都市| 惠水县| 昌黎县| 连江县| 营山县| 麻江县| 宿松县| 巴东县| 商洛市| 涿州市| 铅山县| 吉首市| 北流市| 桂林市| 武汉市| 龙门县| 绿春县| 太白县| 根河市| 柏乡县| 苗栗市| 正宁县| 阳朔县| 鹤壁市| 临邑县| 桐乡市| 安徽省| 清原| 长沙县| 右玉县| 长寿区| 垫江县| 乌拉特中旗| 临夏市| 东安县| 高台县| 泰和县|