[Avg. reading time: 7 minutes]
Iterator in Rust
What is Iteration?
Iteration means traversing a collection of values one by one.
In Rust, this can be done using:
- Traditional loops
- Iterators
Both achieve the same goal, but they follow different programming styles and mental models.
Loops vs Iterators
Loops – Imperative Style
Loops are Imperative. You must mention how often to loop over and follow Procedural-style programming.
- You control index
- You control bounds
- You control increment
- You describe how to loop
Example:
fn main() { let ages = [27, 35, 40, 10, 19]; let mut index = 0; while index < ages.len() { let age = ages[index]; println!("Age = {:?}", age); index += 1; } }
Here you manually:
- Track position
- Check length
- Increment counter
Iterators - Declarative Style
Iterators are Declarative. This means it specifies what to do instead of how to do it and follows Functional Style programming.
- You describe what should happen
- Rust handles the iteration logic
- Cleaner and safer
- Encourages functional programming patterns
// Using Iterator fn main() { let ages = [27, 35, 40, 10, 19]; let ages_iterator = ages.iter(); for age in ages_iterator { println!("Age = {:?}", age); } }
- No index.
- No manual bounds checking.
- No increment logic.
Rust abstracts that away.
Apart from iter(), Rust supports pure functions such as map, filter, fold, collect
We will discuss about Vec_ in next chapter
fn main() { let ages = [27, 35, 40, 10, 19]; let adults: Vec<_> = ages .iter() .filter(|&&age| age >= 18) .map(|&age| age * 2) .collect(); println!("{:?}", adults); }
Manually navigating to next iterator value
fn main() { let ages = [27, 35, 40, 10, 19]; let mut ages_iterator = ages.iter(); println!("{:?}",ages_iterator.next()); println!("{:?}",ages_iterator.next()); println!("{:?}",ages_iterator.next()); println!("{:?}",ages_iterator.next()); println!("{:?}",ages_iterator.next()); println!("{:?}",ages_iterator.next()); }
Using Loops
fn main() { let ages = [27, 35, 40, 10, 19]; let mut ages_iterator = ages.iter(); while let Some(x) = ages_iterator.next(){ println!("{:?},{}",Some(x),x); } }
fn main() { let ages = [27, 35, 40, 10, 19]; let mut ages_iterator = ages.iter(); // Looping thru Ages Array for age in ages { println!("Age = {:?}", age); } // Manually moving ages_iterator println!("{:?}", ages_iterator.next()); // Looping thru an Iterator. See the additional functionality it offers for age in ages_iterator { println!("Age = {:?}", age); } }
Use Cases
- Stream log processing
- Network packet processing
- ETL style pipelines
- CLI Tools