Iterator

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

  1. struct Fibonacci {
  2. curr: u32,
  3. next: u32,
  4. }
  5. impl Iterator for Fibonacci {
  6. type Item = u32;
  7. fn next(&mut self) -> Option<Self::Item> {
  8. let new_next = self.curr + self.next;
  9. self.curr = self.next;
  10. self.next = new_next;
  11. Some(self.curr)
  12. }
  13. }
  14. fn main() {
  15. let fib = Fibonacci { curr: 0, next: 1 };
  16. for (i, n) in fib.enumerate().take(5) {
  17. println!("fib({i}): {n}");
  18. }
  19. }

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() 不存在。