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);
}
我希望您能在不传递向量所有权的情况下,在子函数中改变向量。子函数需要迭代并改变向量。
然而,上述代码由于以下错误而无法工作:
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;
| ^^^^
我尝试通过可变引用的引用进行迭代,但仍然无法正常工作:
// no change in main function
fn go(v: &mut Vec<i32>) {
for i in &v {
println!("{}", i);
}
v.push(4);
}
我遇到的错误信息:
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;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
那么在我的子函数中迭代该向量并改变向量的正确方法是什么呢?
谢谢!
for i in v
语法吗? - Erben Mointo_iter
,这将导致所有权的移动。 - mxp-xcinto_iter()
可能不是默认的选择。因为当输入是&mut v
时,你仍然可以使用into_iter()
。还是按照上面的问题来,不要听取我的想法。 - mxp-xc