Passing mutable self reference to method of owned object

Currently your Ball struct needs to know about the Field it’s contained in to be able to update itself. This doesn’t compile because the result would be cyclic references combined with mutation. You could make this work by using Cell or RefCell (the latter having a performance cost) but it would be even better to structure the code differently. Let the Field struct check for and resolve BallBall and BallWall collisions. The Ball struct’s update function can handle updating the Ball‘s position.

// Ball's update function
fn update(&mut self) {
    // update position
}

// Field's update function
fn update(&mut self) {
    for ball in self.balls.iter_mut() {
        ball.update();
    }

    // check for collisions

    // resolve any collisions
}

Leave a Comment