I am new to Rust. I need to create a vector before a for loop. Run for loop on it. Change the vector inside the for loop. Then Change the vector after the for loop.
I tried the following code and tried to use immutable borrow but both did not work.
fn main() {
let mut vec1 = vec![4, 5];
vec1.push(6);
for i in vec1 {
if i % 2 == 0 {
vec1.push(7);
}
}
vec1.push(8);
println!("vec1={:?}", vec1);
}
I expect to compile and change the vector inside and after the for loop. But it shows this error message:
error[E0382]: borrow of moved value: `vec1`
--> src/main.rs:6:13
|
2 | let mut vec1 = vec![4, 5];
| -------- move occurs because `vec1` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 | vec1.push(6);
4 | for i in vec1 {
| ----
| |
| value moved here
| help: consider borrowing to avoid moving into the for loop: `&vec1`
5 | if i % 2 == 0 {
6 | vec1.push(7);
| ^^^^ value borrowed here after move
Can you explain why move occurs? Can you make it compile?