我刚接触Rust。 我需要在for循环之前创建一个向量。 在其上运行for循环。 更改for循环中的向量。 然后在for循环之后更改向量。
我尝试了以下代码并尝试使用不可变借用,但两者都没有起作用。
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);
}
我希望在for循环内部和之后编译并更改向量,但它显示了这个错误信息:
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
你能解释移动为什么会发生吗?你能让它编译通过吗?