How to run for loop on elements of a vector and change the vector inside the for loop and outside the for loop in rust?

There are two problems with your code. Luckily, both of them can be solved by changing one thing. The problems are:

  • Writing for _ in vec1 moves the value vec1 into the loop. This is a move like every other move, meaning that the value is not accessible after the loop! If you need a refresher on ownership and moving, please read the related chapter in the Rust book. You can iterating over references to a vector's elements via for _ in &vec1.
  • You are trying to mutate the vector you are iterating over. Regardless of whether you iterate over the vector by value (as you do) or by reference, you cannot change the vector while iterating over it. And there are many good reasons for that! In your case, you could easily end up having an infinite loop if you add elements while iterating.

To solve both problems at the same time, you can iterate over indices to the vector instead of the vectors elements (Playground):

let mut vec1 = vec![4, 5];
vec1.push(6);
for i in 0..vec1.len() {
    if vec1[i] % 2 == 0 {
        vec1.push(7);
    }
}
vec1.push(8);
println!("vec1={:?}", vec1);

This way, the vector is not moved nor borrowed by the for loop and we are free to mutate it during and after the loop. This particular solution iterates over the indices of the original vector, meaning that elements added in the loop are not iterated over by the loop. This is a good protection to avoid accidental infinite loops. Please note, however, that you can still shoot yourself in the foot by, for example, removing elements from the vector during iteration. In general, independent of programming language, mutating collections while iterating over them is dangerous and should only be done with care.