Iterator

Iterator 特徵可讓您對集合中的值進行疊代作業。這需要用到 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() 也無妨。