Mutable borrow in nested loops

⚓ Rust    📅 2026-01-10    👤 surdeus    👁️ 1      

surdeus

I need to borrow values in the vector (particle_vec) and change their properties, but I can't borrow them as mutable.

(Note: I am not quite sure if I should use RefCell. Please forgive my lack of knowledge about these functionalities.)

pub struct Space(RefCell<Vec<Particle>>);
pub fn gravity_force(&mut self) {
        let Space(particle_vec) = self;
        let borrow_p = particle_vec.borrow_mut();

        for p in borrow_p.iter() {
            for q in borrow_p.iter() {
                if p == q {
                    continue;
                }

                let x_distance = p.coord.0 - q.coord.0;
                let y_distance = p.coord.1 - q.coord.1;                
                let distance = ((x_distance.pow(2) + y_distance.pow(2)) as f32).sqrt() as i16;
                let force_quantity_x = (x_distance/distance)*((p.mass*q.mass)/(distance as u16)) as i16;
                let force_quantity_y = (y_distance/distance)*((p.mass*q.mass)/(distance as u16)) as i16;

                p.apply_force((force_quantity_x, force_quantity_y));
                q.apply_force((force_quantity_x, force_quantity_y));
            }
        }
    }

Particle struct looks like this:

// Imaginary, point-like particles
#[derive(Clone)]
pub struct Particle {
    // universal mass unit (umu)
    mass: u16,
    // universal distance unit (udu)
    coord: (i16, i16),
    // time unit: universal time unit (utu)
    // composes universal time frame (utf, which is equal to one loop cycle)
    velocity: (i16, i16),
    // unique particle identification number
    id: u16
}

apply_force changes their velocity and that is, essentially, what I need in this function. I can't make borrow checker understand that I don't need to borrow the same element in the same vector but different elements in the same vector.

Any kind of help would be appreciated.

6 posts - 3 participants

Read full topic

🏷️ Rust_feed