An iterator gives you items one at a time, like dealing cards from a deck. Call `.into_iter()` on a vector when you want an iterator that takes its items by value rather than borrowing them. The vector is consumed, so you cannot use it afterward. section 8.2
Choose the method that matches what you need to do with the items:
- `.iter()` borrows items as references, leaving the vector available. section 8.2
- `.iter_mut()` borrows items as mutable references so you can change them. section 8.2
- `.into_iter()` takes items by value, consuming the vector. section 8.2
fn main() {
let vector1 = vec![1, 2, 3];
let vector1_a = vector1
.iter() #1
.map(|x| x + 1)
.collect::<Vec<i32>>();
let vector1_b = vector1
.into_iter()
.map(|x| x * 10)
.collect::<Vec<i32>>();
let mut vector2 = vec![10, 20, 30];
vector2.iter_mut().for_each(|x| *x +=100);
println!("{:?}", vector1_a);
println!("{:?}", vector1_b);
println!("{:?}", vector2);
}
The first chain uses `.iter()` to make a new vector while keeping `vector1`. The second uses `.into_iter()` to make another vector, consuming `vector1`. In both chains, `.collect()` turns the iterator's results into a `Vec`. section 8.2
You can also pass an owned vector directly to a `for` loop instead of writing `.into_iter()` explicitly. Once you have an iterator, methods such as `.map()` can transform its items; an iterator chain does no work until it is consumed, for example by `.collect()`. section 8.2 section 8.3.2
use std::collections::HashMap;
fn main() {
let some_keys = vec![0, 1, 2, 3, 4, 5];
let some_values = vec!["zero", "one", "two", "three", "four", "five"];
let number_word_hashmap = some_keys
.into_iter() #1
.zip(some_values.into_iter()) #2
.collect::<HashMap<_, _>>();
println!(
"The value at key 2 is: {}",
number_word_hashmap.get(&2).unwrap()
);
}
Two vectors become value iterators. `.zip()` pairs their items, and `.collect()` builds a `HashMap` from those pairs. section 8.3.2

