【发布时间】:2020-04-21 19:55:26
【问题描述】:
我需要遍历一个可变向量,并且在 for 循环中我还需要将向量传递给一个修改当前对象的函数。
pub struct Vector2 {
x: f64,
y: f64,
}
pub struct Planet {
position: Vector2,
init_velocity: Vector2,
curr_velocity: Vector2,
radius: f64,
mass: f64,
}
impl Planet {
pub fn update_velocity(
&mut self,
other_planets: &Vec<Planet>,
grav_constant: f64,
timestep: f64,
) {
for p in other_planets {
// Calculate self's velocity relative to all other planets
}
}
pub fn update_position(&mut self) {
self.position.x = self.position.x + self.curr_velocity.x;
self.position.y = self.position.y + self.curr_velocity.y;
}
}
fn main() {
let mut planets = Vec::<Planet>::new();
planets.push(Planet {
position: Vector2 { x: 10.0, y: 10.0 },
init_velocity: Vector2 { x: 1.0, y: 1.0 },
curr_velocity: Vector2 { x: 1.0, y: 1.0 },
radius: 20.0,
mass: 500.0,
});
for p in &mut planets {
p.update_velocity(&planets, 0.0000000000674 as f64, 0.0);
p.update_position();
}
}
error[E0502]: cannot borrow `planets` as immutable because it is also borrowed as mutable
--> src/main.rs:42:27
|
41 | for p in &mut planets {
| ------------
| |
| mutable borrow occurs here
| mutable borrow later used here
42 | p.update_velocity(&planets, 0.0000000000674 as f64, 0.0);
| ^^^^^^^^ immutable borrow occurs here
由于存在可变的行星借用,因此不可能创建不可变的甚至另一个可变的值,而且我找不到解决这个难题的方法。
【问题讨论】:
-
这很奇怪,因为我刚刚问了几乎相同的问题,似乎无法在任何地方找到并回答。
-
其他行星也包含当前行星,不会有问题吗?
-
可以,但我可以通过提供行星 ID 来解决这个问题,然后跳过与当前 ID 匹配的行星
标签: for-loop rust immutability mutable borrowing