I am doing the Rust by Example tutorial which has this code snippet:
// Vec example
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// `iter()` for vecs
I (a Rust newbie) came here from Google seeking a simple answer which wasn't provided by the other answers. Here's that simple answer:
iter()
iterates over the items by referenceinto_iter()
iterates over the items, moving them into the new scopeiter_mut()
iterates over the items, giving a mutable reference to each itemSo 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
.
This was helpful: http://hermanradtke.com/2015/06/22/effectively-using-iterators-in-rust.html
Making this a community wiki so that hopefully a Rust pro can edit this answer if I've made any mistakes.