Difference between iter, iter_mut, and into_iter in Rust example
Rust provides different iterators to iterate an element in a Collection.
It provides three types of methods to iterate a vector or array.
- iter()
- iter_mut()
- into_iter()
The above three provide an iterator to navigate each element of a collection of objects.
Then, What is the difference between those?
Difference between iter, into_iter, and iter_mut?
iter() function
These functions iterate elements using reference or pointer.
Let’s see an example of how to iterate a vector v
v.iter()
function is equal to &v
, that means iterated retrued with this function &V by convention.
Here is an example
fn main() {
let v = vec![0, 1, 2, 3];
// v.iter example
for item in &v {
print!("{} ", item);
}
for item in v.iter() {
print!("{} ", item);
}
}
Output:
0 1 2 3 0 1 2 3
iter_mut() function
These functions iterate the elements in the collections, allowing each element has a reference to mutate its value.
v.iter_mut()
function is equal to mut &v
, that means iterated retrued with this function &V by convention.
fn main() {
// v.iter_mut() function example
let mut v1 = vec![0, 1, 2, 3];
for item in &mut v1 {
*item *= 2;
println!("{} ", item);
}
for item in v1.iter_mut() {
*item *= 2;
println!("{} ", item);
}
}
Output:
0
2
4
6
0
4
8
12
into_iter() function
It is a generic method to return an iterator, where each iterator holds element value, mutable and immutable references based on usage.
It is equal to combination of iter() and iter_mut(). It implements std::iter::IntoIterator
trait
v.into_iter() returns an iterator that contains value, &v, mut &V.
fn main() {
let v = vec![0, 1, 2, 3];
let mut v1 = vec![0, 1, 2, 3];
// v.iter example
for item in &v {
print!("{} ", item);
}
for item in v.into_iter() {
print!("{} ", item);
}
}
Output:
0 1 2 3 0 1 2 3