Rust iter and into iter

来自WHY42
  • iter() iterates over the items by reference
  • iter_mut() iterates over the items, giving a mutable reference to each item
  • into_iter() iterates over the items, moving them into the new scope

So for x in my_vec { ... } is essentially equivalent to my_vec.into_iter().for_each(|x| ... ) - both move the elements of my_vec into the ... scope.

If you just need to look at the data, use iter, if you need to edit/mutate it, use iter_mut, and if you need to give it a new owner, use into_iter.[1] [2]