Iteradores
Se puede implementar el trait Iterator en tus propios tipos:
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}"); } }
-
El trait
Iteratorimplementa 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. -
IntoIteratores el trait que hace que los bucles funcionen. Se implementa a través de tipos de colecciones, comoVec<T>, y de referencias a ellas, como&Vec<T>y&[T]. Los intervalos también lo implementan. Esta es la razón por la que se puede iterar sobre un vector confor i in some_vec { .. }, perosome_vec.next()no existe.