Rust iter and into iter

来自WHY42
Riguz留言 | 贡献2024年6月26日 (三) 10:04的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
  • 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]