Rust Analyzer or Compiler did not warn!

Here is my code:

fn main()
{
   let mut v  = vec!["yousuf".to_string(), "fahad".to_string()];

   for s in  &mut v
   {
        println!("{}", s);
   }   
   println!("{:?}", v);
}

I think the code is straightforward. Neither did I mutate the vector nor its element after taking a mutable reference to vector v in the for loop. I thought the Rust analyzer would warn about not using mut word before v initialization as I did not mutate it anywhere.

Any ideas?

Thanks.

You will never get an "unused mut" warning if you pass a mutable reference to a function. And you are indeed doing that, since the for loop is equivalent to this:

fn main() {
    let mut v = vec!["yousuf".to_string(), "fahad".to_string()];

    let mut v_iter = std::iter::IntoIterator::into_iter(&mut v);
    while let Some(s) = v_iter.next() {
        println!("{}", s);
    }
    println!("{:?}", v);
}

So you're passing a mutable reference to v into the function <&mut Vec<String> as IntoIterator>::into_iter.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.