我有一个for
循环,会遍历一个Point
结构体的切片。在循环中,Point
的一些字段将被修改,因此包含循环的函数需要对切片进行可变引用。
当我需要将一个(不可变)引用传递给在可变引用上迭代的for
循环内部的函数时,问题就出现了:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut grid = vec![];
grid.push(Point { x: 10, y: 10 });
grid.push(Point { x: -1, y: 7 });
calculate_neighbors(&mut grid);
}
fn calculate_neighbors(grid: &mut [Point]) {
for pt in grid.iter_mut() {
pt.x = nonsense_calc(grid);
}
}
#[allow(unused_variables)]
fn nonsense_calc(grid: &[Point]) -> i32 {
unimplemented!();
}
error[E0502]: cannot borrow `*grid` as immutable because it is also borrowed as mutable
--> src/main.rs:18:30
|
17 | for pt in grid.iter_mut() {
| ---------------
| |
| mutable borrow occurs here
| mutable borrow used here, in later iteration of loop
18 | pt.x = nonsense_calc(grid);
| ^^^^ immutable borrow occurs here
编译器报错,因为已经存在可变借用,所以无法将
grid
借用为不可变。这是正确的,我也能看出它试图防止什么问题,但我该如何实现我的需求呢?理想情况下,我不想创建 grid
的副本,因为这可能很昂贵。