Iterator

'Iterator' trait 支持迭代集合中的值。它需要用到 next 方法,并提供很多方法。许多标准库类型均能实现 Iterator,您也可以自行实现:

struct Fibonacci {
    curr: u32,
    next: u32,
}

impl Iterator for Fibonacci {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        let new_next = self.curr + self.next;
        self.curr = self.next;
        self.next = new_next;
        Some(self.curr)
    }
}

fn main() {
    let fib = Fibonacci { curr: 0, next: 1 };
    for (i, n) in fib.enumerate().take(5) {
        println!("fib({i}): {n}");
    }
}
This slide should take about 5 minutes.
  • The Iterator trait implements many common functional programming operations over collections (e.g. map, filter, reduce, etc). This is the trait where you can find all the documentation about them. In Rust these functions should produce the code as efficient as equivalent imperative implementations.

  • IntoIterator 是迫使 for 循环运作的特征。此特征由集合类型 (例如 Vec<T>)和相关引用(例如 &Vec<T>&[T])而实现。此外,范围也会实现这项特征。因此, 您可以使用 for i in some_vec { .. } 来遍历某矢量,但 some_vec.next() 不存在。