13.7 Additional Topics
Beyond the standard adapters and consumers, Rust’s iterator system includes more sophisticated techniques like merging, splitting, zipping, and more.
13.7.1 Iterator Methods vs. for
Loops
for
Loops: Excellent for simple iteration and clarity on ownership.- Iterator Methods: Great for chaining multiple operations or short-circuiting logic.
Using a for
loop:
fn main() { let numbers = vec![1, 2, 3]; for n in &numbers { println!("{}", n); } }
Using for_each()
:
fn main() { let numbers = vec![1, 2, 3]; numbers.iter().for_each(|n| println!("{}", n)); }
13.7.2 Chaining and Zipping Iterators
Chaining concatenates elements from two iterators:
fn main() { let nums = vec![1, 2, 3]; let letters = vec!["a", "b", "c"]; let combined: Vec<String> = nums .iter() .map(|&n| n.to_string()) .chain(letters.iter().map(|&s| s.to_string())) .collect(); println!("{:?}", combined); // ["1", "2", "3", "a", "b", "c"] }
Zipping pairs up elements from two iterators:
fn main() { let nums = vec![1, 2, 3]; let letters = vec!["a", "b", "c"]; let zipped: Vec<(i32, &str)> = nums .iter() .cloned() .zip(letters.iter().cloned()) .collect(); println!("{:?}", zipped); // [(1, "a"), (2, "b"), (3, "c")] }