What is the difference between iter and into_iter?

后端 未结 4 929
情书的邮戳
情书的邮戳 2020-11-22 14:18

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         


        
4条回答
  •  没有蜡笔的小新
    2020-11-22 14:51

    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 reference
    • into_iter() iterates over the items, moving them into the new scope
    • iter_mut() iterates over the items, giving a mutable reference to each item

    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.

    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.

提交回复
热议问题