Programming Languages
Rust
Subjective
Oct 04, 2025
Explain iterators in Rust and their lazy evaluation.
Detailed Explanation
Iterators in Rust:
• Lazy evaluation - no work until consumed
• Iterator trait with next() method
• Adapters transform iterators
• Consumers execute the iterator
• Zero-cost abstractions
Example:
let v = vec![1, 2, 3, 4, 5];
// Lazy - no work done yet
let iter = v.iter()
.map(|x| x * 2)
.filter(|&x| x > 4);
// Consumer - work is done here
let results: Vec = iter.collect();
// Chain operations
let sum: i32 = v.iter().map(|x| x * x).sum();
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts