1

The Vec type has an implementation of the IntoIterator trait for mutable vectors:

impl<'a, T> IntoIterator for &'a mut Vec<T> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;

    fn into_iter(self) -> slice::IterMut<'a, T> {
        self.iter_mut()
    }
}

I am not able to get that code invoked. I am trying:

let mut vec = vec![1, 2, 3];
for mut i in &vec {
    println!("{}", i);
}

What usage of Vec will invoke that particular IntoIterator implementation?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
pramodbiligiri
  • 355
  • 1
  • 10
  • I think you should call directly wiht _vec.into_iter()_. You don't need to have the vec mutable for that, and even the item _i_ don't need to be mutable, as you're going to have ownership of the vector's items. – Mario Santini Aug 31 '20 at 12:05
  • I think I figured it out. Have added an answer to my own question. – pramodbiligiri Aug 31 '20 at 12:17
  • `mut Vec` is not a type. There is an implementation of `IntoIterator` for `&mut Vec`, and one for `Vec`, as well as the one for `&Vec` which is the one you are calling in this code. – trent Aug 31 '20 at 13:09

1 Answers1

2

The following code will invoke the IntoIterator variant mentioned in the question:

let mut vec = vec![1, 2, 3];
for i in &mut vec {
    println!("{}", i);
}

This is because the vec! macro returns an owned Vec, not a reference. You can mutably iterate over the owned Vec using for i in &mut vec.

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
pramodbiligiri
  • 355
  • 1
  • 10