I need to iterate over a mutable vector, and inside of the for loop I also need to pass the vector into a function that modifies the current object.
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
Because a mutable borrow of planets exists, it's not possible to make an immutable or even another mutable value and I can't see a way around this conundrum.