Difference between iter, iter_mut, and into_iter in Rust example

Rust provides various iterators for traversing elements within a collection.

It offers three types of methods for iterating through a vector or array.

  • iter()
  • iter_mut()
  • into_iter() Each of these methods provides an iterator to traverse each element of a collection.

So, what are the differences between them?

Difference between iter, into_iter, and iter_mut?

  • iter() function These functions iterate elements using references or pointers.

    Let’s see an example of how to iterate through a vector v.

    The v.iter() function is equivalent to &v, meaning it returns an iterator using references conventionally.

    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 through the elements in the collections, allowing each element to have a reference to mutate its value.

    The v.iter_mut() function is equivalent to mut &v, meaning it returns an iterator using mutable references conventionally.

    Here is an example.

    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 function to return an iterator, where each iterator holds element values, mutable and immutable references based on usage.

It is equal to a combination of iter() and iter_mut(). It implements the std::iter::IntoIterator trait.

v.into_iter() returns an iterator that contains values, &v,mut &V.

Here is an example.

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