Interior Mutability

In rust, a variable is declared as mutable or immutable and all of it’s fields (in the case of a struct) are declared the same–you can’t mutate a field while also making a borrow of another field.

This presents a problem for self-referential data structures. For example, in game programming it’s typical to have a top level GameState object that is mutated each frame which often requires reading from a field while mutating another which would cause a borrowck error (trying to take multiple references of GameState).

The solution to this access pattern is interior mutability, wrapping fields you need to mutate in a RefCell. This provides runtime borrow checks with the ability to mutate a field while holding a reference to the struct.

See also:

  • Blog post on interior mutability that recreates Cell to explain how it works
  • Splitting borrows is a similar method for mutating multiple parts of a list