13.7 Additional Topics
13.7.1 Iterator Methods vs. for
Loops
Using a for
Loop:
fn main() { let numbers = vec![1, 2, 3]; for number in &numbers { println!("{}", number); } }
Using for_each()
:
fn main() { let numbers = vec![1, 2, 3]; numbers.iter().for_each(|number| println!("{}", number)); }
When to Use Which:
for
Loops: Simple iterations.- Iterator Methods: Complex chains and functional style.
13.7.2 Chaining and Zipping Iterators
Chaining Iterators:
fn main() { let numbers = vec![1, 2, 3]; let letters = vec!["a", "b", "c"]; let combined: Vec<String> = numbers .iter() .map(|&n| n.to_string()) .chain(letters.iter().map(|&s| s.to_string())) .collect(); println!("{:?}", combined); // Output: ["1", "2", "3", "a", "b", "c"] }
Zipping Iterators:
fn main() { let numbers = vec![1, 2, 3]; let letters = vec!["a", "b", "c"]; let zipped: Vec<(i32, &str)> = numbers.iter().cloned().zip(letters.iter().cloned()).collect(); println!("{:?}", zipped); // Output: [(1, "a"), (2, "b"), (3, "c")] }