Mutable self while reading from owner object

前端 未结 2 431
时光取名叫无心
时光取名叫无心 2020-12-04 03:04

I have one object that owns another. The owned object has a mutating method that depends on non-mutating methods of its owner. The architecture (simplified as much as possib

2条回答
  •  温柔的废话
    2020-12-04 03:16

    In summary: Rust is doing the right thing by refusing to compile what I wrote. There's no way to know at compile time that I won't invalidate the data I'm using. If I get a mutable pointer to one animal, the compiler can't know that my read-only access to the vector isn't invalidated by my mutations to that particular animal.

    Because this can't be determined at compile time, we need some kind of runtime check, or we need to use unsafe operations to bypass the safety checks altogether.

    RefCell is the way to go if we want safety at the cost of runtime checks. UnsafeCell is at least one option to solve this without the overhead, at the cost of safety of course.

    I've concluded that RefCell is preferable in most cases. The overhead should be minimal. That's especially true if we're doing anything even moderately complex with the values once we obtain them: The cost of the useful operations will dwarf the cost of RefCell's checks. While UnsafeCell might be a little faster, it invites us to make mistakes.

    Below is an example program solving this class of problem with RefCell. Instead of animals and feeding, I chose players, walls, and collision detection. Different scenery, same idea. This solution is generalizable to a lot of very common problems in game programming. For example:

    • A map composed of 2D tiles, where the render state of each tile depends on its neighbors. E.g. grass next to water needs to render a coast texture. The render state of a given tile updates when that tile or any of its neighbors changes.

    • An AI declares war against the player if any of the AI's allies are at war with the player.

    • A chunk of terrain is calculating its vertex normals, and it needs to know the vertex positions of the neighboring chunks.

    Anyway, here's my example code:

    use std::cell::RefCell;
    
    struct Vector2 {x: f32, y: f32}
    
    impl Vector2 {
        fn add(&self, other: &Vector2) -> Vector2 {
            Vector2 {x: self.x + other.x, y: self.y + other.y}
        }
    }
    
    struct World {
        players: Vec>,
        walls: Vec
    }
    
    struct Wall;
    
    impl Wall {
        fn intersects_line_segment(&self, start: &Vector2, stop: &Vector2) -> bool {
            // Pretend this actually does a computation.
            false
        }
    }
    
    struct Player {position: Vector2, velocity: Vector2}
    
    impl Player {
        fn collides_with_anything(&self, world: &World, start: &Vector2, stop: &Vector2) -> bool {
            for wall in world.walls.iter() {
                if wall.intersects_line_segment(start, stop) {
                    return true;
                }
            }
    
            for cell in world.players.iter() {
                match cell.try_borrow_mut() {
                    Some(player) => {
                      if player.intersects_line_segment(start, stop) {
                          return true;
                      }
                    },
                    // We don't want to collision detect against this player. Nor can we,
                    // because we've already mutably borrowed this player. So its RefCell
                    // will return None.
                    None => {}
                }
            }
    
            false
        }
    
        fn intersects_line_segment(&self, start: &Vector2, stop: &Vector2) -> bool {
            // Pretend this actually does a computation.
            false
        }
    
        fn update_position(&mut self, world: &World) {
            let new_position = self.position.add(&self.velocity);
            if !Player::collides_with_anything(self, world, &self.position, &new_position) {
                self.position = new_position;
            }
        }
    }
    
    fn main() {
        let world = World {
            players: vec!(
                RefCell::new(
                  Player {
                      position: Vector2 { x: 0.0, y: 0.0},
                      velocity: Vector2 { x: 1.0, y: 1.0}
                  }
                ),
                RefCell::new(
                  Player {
                      position: Vector2 { x: 1.1, y: 1.0},
                      velocity: Vector2 { x: 0.0, y: 0.0}
                  }
                )
            ),
    
            walls: vec!(Wall, Wall)
        };
    
        for cell in world.players.iter() {
            let player = &mut cell.borrow_mut();
            player.update_position(&world);
        }
    }
    

    The above could be altered to use UnsafeCell with very few changes. But again,I think RefCell is preferable in this case and in most others.

    Thanks to @DK for putting me on the right track to this solution.

提交回复
热议问题