Rust refrence to Box causing lifetime issues

41 views Asked by At

I'm trying to build a little physics system in rust just to help me learn rust.

I am trying to set up the architecture the following way:

  • Solver has a vector of Bodies.
  • Body has a vector of Particles and a vector of Sticks.
  • Stick (these are constraints between Particles) has references to Particles.

The code for these are here: https://github.com/bit-shift-io/rust-verlet/tree/main/src/v2

Now I am trying to assemble these parts in this file: https://github.com/bit-shift-io/rust-verlet/blob/main/src/scenes/car/car_scene.rs

On line 45 of the above file, I get the error:

cannot borrow `body` as mutable because it is also borrowed as immutable
mutable borrow occurs hererustcClick for full compiler diagnostic
car_scene.rs(38, 27): immutable borrow occurs here
car_scene.rs(7, 6): lifetime `'a` defined here
car_scene.rs(57, 9): returning this value requires that `body.particles` is borrowed for `'a`

I think what is happening is that I am borrowing from body.particles and passing this Box reference to a Stick which gets added to the same Body as body.particles, and so is causing some circular lifetime.

What I was hoping to achieve was that the life time of Stick would just depend on the Particle lifetime, with the Body having ownership of its particles and sticks. i.e. when a Body is destroyed, its particles and sticks are also cleaned up at that stage.

Yet rust has forced me to have the Stick lifetime applied to the Body, then on the Solver also!

How should I make this work?

0

There are 0 answers