存在可变引用时传递不可变引用

时间:2018-12-20 15:29:04

标签: loops rust borrow-checker mutability

我有一个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!();
}

Playground

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的副本,因为这可能会很昂贵。

1 个答案:

答案 0 :(得分:7)

避免在迭代中借用数组的一种解决方案是使用索引:

fn calculate_neighbors(grid: &mut [Point]) {
    for i in 0..grid.len() {
        grid[i].x = nonsense_calc(grid);
    }
}