Having code that is easier to reason about and where the state cannot be changed is even more important in multithreaded scenarios. This prevents so-called anomalies (or side effects) where the state of an object is changed outside a dependent thread.
Locks are generally made to change the state of a shared object—they secure critical sections, which only a single thread can modify at any given time. Other threads have to "line up" and wait for the lock to be released to access the part as well. In Rust, this is called a mutex.
Locks and mutex zones are bad for the following reasons:
- They have to be in the right order (acquired and released).
- What happens when a thread panics in a mutex zone?
- They are hard to integrate seamlessly into the part of the program that they protect.
- They are a bottleneck for performance.
Immutability is a simple way to avoid all of these, and there are many immutable data structure crates available, including one...