Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterator

El trait Iterator permite iterar valores en una colección. Requiere un método next y proporciona muchos otros métodos. Muchos tipos de bibliotecas estándar implementan Iterator y también está a nuestro alcance:

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.
  • El trait Iterator implementa muchas operaciones comunes de programación funcional en colecciones (por ejemplo, map, filter, reduce, etc.). Este es el trait que te permite encontrar toda la documentación sobre ellas. En Rust, estas funciones deberían generar un código tan eficiente como las implementaciones imperativas equivalentes.

  • IntoIterator es el trait que hace que los bucles funcionen. Se implementa a través de tipos de colecciones, como Vec<T>, y de referencias a ellas, como &Vec<T> y &[T]. Los rangos también lo implementan. Esta es la razón por la que se puede iterar sobre un vector con for i in some_vec { .. }, pero some_vec.next() no existe.