Skip to content
Comfy Engine

Game state and the borrow checker: patterns that stop the fight

Game state and the borrow checker: patterns that stop the fight

Every Rust game reaches the same afternoon. You have a World with a list of entities, the player wants to hit the nearest enemy, and the compiler refuses: you cannot borrow world.entities as mutable because it is also borrowed as immutable. You add a .clone(), then another, then a RefCell, and somehow the code compiles but you no longer trust it. The good news is that this is not a sign that Rust is bad at games. It is the compiler pointing at a real question about who is allowed to change what, and when. The answers are a handful of patterns that turn up again and again. This piece is organised by symptom: the error you are looking at, why it happens, and what I reach for instead.

Symptom 1: "cannot borrow as mutable because it is also borrowed as immutable"

This is the classic. Some code like this:

let target = world.enemies.iter().min_by(|a, b| a.dist.total_cmp(&b.dist));
if let Some(enemy) = target {
    world.player.score += 1;   // fine, different field
    world.enemies.retain(|e| e.id != enemy.id); // error: enemy still borrows enemies
}

The target is a reference into world.enemies. While it lives, the vector cannot be modified, because modifying it could move or free the memory that reference points at. In C++ this would compile and occasionally crash. Rust stops you at build time.

What I do instead: stop holding the reference. Copy out the small piece of data you need, usually an id or an index, and let the borrow end.

let target_id = world.enemies
    .iter()
    .min_by(|a, b| a.dist.total_cmp(&b.dist))
    .map(|e| e.id);
if let Some(id) = target_id {
    world.enemies.retain(|e| e.id != id);
}

map(|e| e.id) turns the reference into a plain u32 (or whatever your id type is), which is Copy. The borrow of enemies ends at the semicolon, and the mutation is legal. This is the first and most useful habit: find, then act, in two separate statements.

Symptom 2: references stored inside structs

The next stage is trying to store relationships. A homing missile wants to remember its target, so you write struct Missile<'a> { target: &'a Enemy }. Lifetimes spread through every type that touches a missile, and eventually you need to push a new enemy while a missile is pointing at an old one, and nothing compiles.

What I do instead: store indices or ids, never references, in game state. A missile holds target: EnemyId. Each frame it looks the target up, and if the lookup fails, the target has died and the missile can retarget or fizzle.

Plain usize indices into a Vec have one trap: if enemy 3 dies and you reuse slot 3 for a new enemy, the missile happily chases the newcomer. The fix is a generational index, which pairs the slot with a counter that increases every time the slot is reused.

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Handle { index: u32, generation: u32 }

struct Slot<T> { generation: u32, value: Option<T> }

struct Pool<T> { slots: Vec<Slot<T>>, free: Vec<u32> }

impl<T> Pool<T> {
    fn get(&self, h: Handle) -> Option<&T> {
        let slot = self.slots.get(h.index as usize)?;
        if slot.generation != h.generation { return None; }
        slot.value.as_ref()
    }
    fn remove(&mut self, h: Handle) -> Option<T> {
        let slot = self.slots.get_mut(h.index as usize)?;
        if slot.generation != h.generation { return None; }
        slot.generation += 1;
        self.free.push(h.index);
        slot.value.take()
    }
}

get refuses any handle whose generation does not match the slot, and remove bumps the generation so every old handle to that slot goes stale at once. Insertion (not shown) pops a free index or pushes a new slot and returns a handle with the current generation. Several crates offer this structure ready made, and ECS libraries use the same idea for entity ids, which is one reason an ECS for 2D games sidesteps so many of these fights. Writing your own pool once is still worth it, if only to see that there is no magic.

A quick sizing check for the worried: a Handle of two u32 values is 8 bytes. Ten thousand missiles holding one handle each is 80 kilobytes. That is not a number to lose sleep over.

Symptom 3: "cannot borrow *self as mutable more than once"

This one appears when methods call methods. self.update_physics() takes &mut self, and inside it you call self.spawn_particles(&mut self.particles), and the compiler objects that you are borrowing self twice.

The borrow checker reasons about method calls at the level of the whole self. It does not look inside spawn_particles to see that it only touches particles. But inside a single function, it does reason about individual fields.

What I do instead: split borrows explicitly. Borrow the fields you need as separate local variables, then pass them to free functions that take only what they use.

fn update(&mut self, dt: f32) {
    let Self { bodies, particles, rng, .. } = self;
    for body in bodies.iter_mut() {
        body.y += body.vy * dt;
        if body.y < 0.0 {
            spawn_dust(particles, rng, body.x);
        }
    }
}

The destructuring let Self { bodies, particles, rng, .. } = self; gives three independent mutable borrows of three different fields, which the compiler is perfectly happy with. spawn_dust takes &mut Vec<Particle> and &mut Rng, not &mut self, so it cannot accidentally reach into bodies while you iterate it.

This pattern has a pleasant side effect: function signatures start documenting what each system actually touches. When spawn_dust takes particles and a random generator and nothing else, you know at a glance it cannot move the player.

Symptom 4: iterating while adding or removing

An enemy dies and should drop a coin. You are iterating world.enemies mutably, and pushing to world.pickups is fine thanks to split borrows, but what if dying enemies should also spawn more enemies, or an explosion should damage other enemies in the same list?

You cannot push to a Vec while iterating it, and you cannot hold a mutable reference to one element while reading its neighbours.

What I do instead: a command queue. During iteration, systems do not change the world directly for anything structural. They push small descriptions of what they want to happen into a list, and after the loop, you apply that list.

enum Command { Spawn(EnemyKind, f32, f32), Damage(Handle, i32), Despawn(Handle) }

let mut commands = Vec::new();
for (h, e) in world.enemies.iter() {
    if e.hp <= 0 {
        commands.push(Command::Despawn(h));
        if e.kind == EnemyKind::Splitter {
            commands.push(Command::Spawn(EnemyKind::Small, e.x - 8.0, e.y));
            commands.push(Command::Spawn(EnemyKind::Small, e.x + 8.0, e.y));
        }
    }
}
world.apply(commands);

This assumes the pool from symptom 2 has grown an iter method that yields each live handle alongside a reference to its value, which is a short loop over the slots that skips the empty ones. The loop only reads. Everything that changes the shape of the world is deferred. This looks like extra ceremony for a jam, but it buys you three things beyond compiling: the order of changes is deterministic, you can log or replay the command list when debugging, and you can decide in one place what happens when two commands conflict (two bullets killing the same enemy, for instance, where the second Despawn should do nothing because its handle is already stale).

The command list also slots neatly into a fixed timestep loop: simulate, collect commands, apply commands, render. Each phase has a clear owner of the data.

Symptom 5: you reached for Rc<RefCell<T>> and now things panic

Shared ownership with interior mutability is the escape hatch everyone finds. Rc<RefCell<Enemy>> lets the missile and the enemy list both hold the same enemy, and either can call borrow_mut(). It compiles. Then, at runtime, a BorrowMutError panic appears because some code path borrowed the same cell twice.

RefCell does not remove the borrow rules. It moves them from compile time to run time. Instead of the compiler telling you about the conflict, a panic tells you, possibly only on the one level where two enemies overlap in a particular way.

I do not ban RefCell. Some honest uses:

  • A cache or a counter that is logically read only but updates internally, such as a lazily built lookup table.
  • Engine services that are touched rarely and from a few known places, like an audio mixer handle or a debug draw buffer.
  • Prototypes. If it gets an idea on screen this afternoon, fine, as long as there is a note to come back.

What I avoid is Rc<RefCell<T>> as the main shape of the game state. A world full of shared mutable cells makes it hard to reason about order, impossible to parallelise later, and moves bugs from the build to the player's machine.

A comparison, for when you are deciding

Pattern Cost Best for Watch out for
Copy out an id, then act none one off lookups holding the reference by accident
Generational handles small, a lookup per access relationships between entities forgetting to check for None
Split borrows none systems touching several fields very long destructuring lines
Command queue an allocation per frame, reusable spawning, despawning, cross entity effects commands applied in a surprising order
RefCell runtime check, possible panic caches, rare services becoming the default

What to try next

None of these patterns are exotic. They are the same ideas a C++ engine would use for safety, written down where the compiler can check them. The difference is that Rust makes you choose one on day one instead of after the first crash report.

Take one system in your game that currently clones a Vec to get around the borrow checker. Rewrite it with a command queue: read the world, push commands, apply them afterwards. Then count the clones you removed and run the game under a profiler for a minute to see whether the frame time moved. In my experiments it is usually a small improvement, but the real gain is that the next feature you add to that system will not start with an argument with the compiler. If your project is still at the "one big struct" stage, the walkthrough on how to make a game engine shows how to split that struct into pieces that each pattern above can work with.

Filed in Rust Gamedev

Written by Kasimir Lund

Kasimir writes about Rust for games: engine internals, ownership patterns that survive a real game loop, and getting builds onto other people's machines. He has been writing small engines for himself since the SDL days and lives in Gothenburg.

Keep reading