fn main() {
let mut v = vec![1, 2, 3];
go(&mut v);
// still need v here, so I can't pass ownership to the "go' method above
println!("{}", v.len())
}
fn go(v: &mut Vec<i32>) {
for i in v {
println!("{}", i);
}
v.push(4);
}
I want to mutate a vector in a child function without passing the ownership of that vector. The child function needs to iterate the vector and mutate it.
However the code above does not work due to the following error:
error[E0382]: borrow of moved value: `v`
--> src/main.rs:14:5
|
10 | fn go(v: &mut Vec<i32>) {
| - move occurs because `v` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
11 | for i in v {
| -
| |
| `v` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&v`
...
14 | v.push(4);
| ^^^^^^^^^ value borrowed here after move
|
note: this function takes ownership of the receiver `self`, which moves `v`
--> /Users/moerben/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:234:18
|
234 | fn into_iter(self) -> Self::IntoIter;
| ^^^^
I tried iterating through the reference of the mutable reference and it still does not work:
// no change in main function
fn go(v: &mut Vec<i32>) {
for i in &v {
println!("{}", i);
}
v.push(4);
}
error I got:
error[E0277]: `&&mut Vec<i32>` is not an iterator
--> src/main.rs:11:14
|
11 | for i in &v {
| ^^ `&&mut Vec<i32>` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&&mut Vec<i32>`
= note: required because of the requirements on the impl of `IntoIterator` for `&&mut Vec<i32>`
note: required by `into_iter`
--> /Users/moerben/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:234:5
|
234 | fn into_iter(self) -> Self::IntoIter;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So what is the correct way to iterate through that vector in my child function and then mutate the vector?
Thanks!