Shared Mutability in Rust

Andrew Pritchard
The Startup
Published in
8 min readAug 26, 2019

--

Summary

  • For the majority of code, shared mutability is usually not required.
  • We cannot have sharing, mutability and “internal consistency”. A program that tries to have all three is provably incorrect.
  • If we want sharing, and mutability but do not need “internal consistency”, we can use a file, a database handle, a mutex, or any other similar structure.
  • If we need mutability, and “internal consistency” but do not need sharing, we can have all modifications go through a common ancestor.
  • If we need sharing, and “internal consistency” but not mutability, we can freeze our data, or have persistent data structures.

The problem with shared mutability.

Safe Rust provides us with some guarantees: namely safe memory access, no undefined behaviour, and no data races. In addition to this, safe Rust makes it difficult (but not impossible) to have memory leaks, mutate structures through immutable references, or create memory cycles.

I’ll start by saying that these things are made difficult to do because they are difficult to reason about. Safe rust introduces some resistance so that programmers are more likely to design their programs in such a way that they are more likely to be correct.

If we ignore IO or interior mutability for a moment, safe Rust has property that whenever you hold an immutable reference to an object, the holder of the reference…

--

--

Andrew Pritchard
The Startup

The stories I write are a part of a learning journey through life, logic and programming. Share this journey with me.