Rust iter and into iter:修订间差异

来自WHY42
Riguz留言 | 贡献
创建页面,内容为“* 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…”
 
Riguz留言 | 贡献
无编辑摘要
 
第8行: 第8行:
<ref>https://hermanradtke.com/2015/06/22/effectively-using-iterators-in-rust.html/</ref>
<ref>https://hermanradtke.com/2015/06/22/effectively-using-iterators-in-rust.html/</ref>


[[Category::Rust]]
[[Category:Rust]]
[[Category::Programming]]
[[Category:Programming]]

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]