🦀 Rust
Beginner
What are iterators and the Iterator trait in Rust?
Answer
The Iterator trait in Rust requires implementing a single method: fn next(&mut self) -> Option<Self::Item>. It returns Some(item) for each element and None when exhausted. In practice, you rarely implement next() manually — you use the rich set of iterator adapters that the trait provides: map() (transform each element), filter() (keep elements matching a predicate), flat_map(), take(n), skip(n), zip(), enumerate() (add index), and consumers like collect() (gather into a collection), fold(), sum(), any(), all(). Rust iterators are lazy: adapters build a pipeline that does no work until a consumer is called. This is a zero-cost abstraction — the compiler optimizes iterator chains into tight loops.