Iterators

Iterator Trait

Rust by example - iterators

Iterators allow you to process a sequence of items. An iterator is any type that implements the Iterator trait. This trait requires only one method: next(). Iterators are lazy, meaning they don't do any work until you ask for the next item (via next()).

pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    // ... other methods ...
}

The next() method returns an Option<Self::Item>. If there is a next item, it returns Some(item), otherwise it returns None.

Create an Iterator

Many types in Rust implement IntoIterator, which provides a method into_iter() that returns an iterator.

/// This example demonstrates the difference between `iter()` and `into_iter()`.
fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec![4, 5, 6];

    // `iter()` for `Vec<i32>` yields `&i32`, which we
    // destructured via the `&x` pattern.
    // It only borrows `vec1` and its elements,
    // so they can be used again.
    println!("2 in vec1: {}", vec1.iter().any(|&x| x == 2));

    // `into_iter()` for vecs yields `i32`. No destructuring is required.
    // `into_iter()` does move `vec2` and its elements, so they cannot be
    // used again
    println!("2 in vec2: {}", vec2.into_iter().any(|x| x == 2));
}

Related Topics

  • Closures.
  • Data Structures.
  • Functional Programming.
  • Vectors.

See Also

Iterators⮳.