hi guys, I am new to rust, and I just encountered a confusing problem.
fn main(){
let mut vec = vec![1,2,3];
foo(&mut vec);
}
fn foo(vec: &mut Vec<i32>){
for item in vec{
print!("{}", item);
}
vec.push(4);
}
In the above code snippet, the foo function. rustc said "borrowed of moved value: vec"
error[E0382]: borrow of moved value: `vec`
--> src/main.rs:11:5
|
7 | fn foo(vec: &mut Vec<i32>){
| --- move occurs because `vec` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
8 | for item in vec{
| ---
| |
| `vec` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&vec`
...
11 | vec.push(4);
| ^^^ value borrowed here after move
|
note: this function takes ownership of the receiver `self`, which moves `vec`
--> /Users/steve/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:232:18
|
232 | fn into_iter(self) -> Self::IntoIter;
| ^^^^
What I know is, if you iterate over a vector, which does not implement the Copy trait, it will move. The reason why it moved is rust called a method .into_iter(), which takes the ownership of the Vec.
The confusing part about my code is the vec(parameter of funciont foo) is of type &mut Vec, not of the type Vec. The type of item(variable in the for loop of function foo) is &mut i32, as the IDEA tells me. And with the info( vec
moved due to this implicit call to .into_iter()
) generated by the compiler, what i should do is to call the method into_iter() explictly. Error disappears when i did this, but the type of item is still &mut i32, what is the difference? last confusing point, when I iterate the vec(&mut Vec<i32) in my code, what does the compiler do? dereferences the vec and calls into_iter()?
I am not native in English, so perhaps the expression of my issue is not clear, sorry for that.
Thanks for ur help in advance, i do appreciate that!