当存在可变引用时传递不可变引用
Passing an immutable reference when a mutable reference exists
我有一个 for
循环遍历一片 Point
结构。 Point
s 将在循环中修改一些字段,因此包含循环的函数需要对切片的可变引用。
当我需要将指向切片的(不可变)引用传递给迭代可变引用的 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
的副本,因为这可能很昂贵。
避免为迭代借用数组的解决方案是使用索引:
fn calculate_neighbors(grid: &mut [Point]) {
for i in 0..grid.len() {
grid[i].x = nonsense_calc(grid);
}
}
我有一个 for
循环遍历一片 Point
结构。 Point
s 将在循环中修改一些字段,因此包含循环的函数需要对切片的可变引用。
当我需要将指向切片的(不可变)引用传递给迭代可变引用的 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
的副本,因为这可能很昂贵。
避免为迭代借用数组的解决方案是使用索引:
fn calculate_neighbors(grid: &mut [Point]) {
for i in 0..grid.len() {
grid[i].x = nonsense_calc(grid);
}
}