domingo, 24 de diciembre de 2023

Iterator en Rust


El trait Iterator admite la iteración sobre valores en una colección. Requiere un método next y proporciona muchos métodos. Muchos tipos de bibliotecas estándar implementan Iterator y usted también puede implementarlo usted mismo:


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}");

    }

}


Iterator implementa muchas operaciones de programación funcional comunes sobre colecciones (por ejemplo, mapear, filtrar, reducir, etc.). Este es el rasgo donde puedes encontrar toda la documentación sobre ellos. En Rust, estas funciones deberían producir un código tan eficiente como las implementaciones imperativas equivalentes.

No hay comentarios.:

Publicar un comentario