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;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^那么,在我的子函数中迭代这个向量,然后变异这个向量的正确方法是什么呢?
谢谢!
发布于 2021-12-21 02:38:40
您可以在v.iter()或v.iter_mut()中使用i
发布于 2021-12-21 07:33:21
通常,当您使用可变引用调用方法时,编译器会为您重新借用引用,就像在为什么可变引用不移到这里?中解释的那样,您已经编写了&mut *reference。
泛型参数不被重新借用。IntoIterator::into_iter() ( for循环调用的内容)是泛型的:它采用self,实际上是self: Self,而Self是每个特征的隐藏泛型参数。
您可以看到,即使用简单的IntoIterator::into_iter()调用替换循环,编译器仍然会出错。
fn go(v: &mut Vec<i32>) {
IntoIterator::into_iter(v);
v.push(4);
}游乐场。
编译器确实会为接收方执行重新借用,即使它是泛型的,所以v.into_iter()也可以工作(因此也可以使用for i in v.into_iter() )--但是我们(和for循环去标记)不使用点语法调用into_iter(),这意味着它被当作一个常规函数调用而不是方法。
现在应该很清楚,您可以手动重借它,&mut *v。当然,您也可以使用iter_mut()。
https://stackoverflow.com/questions/70430078
复制相似问题