Before the Action

This text is not intended to serve as a Rust tutorial. However, understanding the concepts outlined here will significantly aid readers in discerning which Rust wrapper to employ.

In Rust, there are two foundational principles:

  1. Ownership: This revolves around various pointer types such as Box, Rc, and Arc. Their primary function is to dictate ownership, determining whether an object has a singular or multiple owners.
  2. Mutability: Various cells, including Cell, RefCell, Mutex, RwLock, and AtomicXXX, play a pivotal role in this domain.

A cornerstone of Rust's safety mechanism is the principle of "Aliasing NAND Mutability." In essence, an object can be mutated safely only when there's no existing reference to its interior. This principle is typically enforced at compile time by the borrow checker:

  • If you possess a &T, you can't simultaneously have a &mut T for the same object in the current scope.
  • Conversely, with a &mut T, holding any other reference to the same object in scope is prohibited.

However, there are scenarios where such restrictions might be overly stringent. At times, one might need or desire the capability to maintain multiple references to an identical object while still having mutation rights. This is where cells come into play.

The constructs of Cell and RefCell are engineered to authorize controlled mutability amidst aliasing:

  • Cell ensures that references to its interior aren't formed, thereby precluding dangling references.
  • RefCell, on the other hand, transitions the enforcement of the "Aliasing XOR Mutability" rule from compile time to runtime.

This mechanism is occasionally termed as "interior mutability." It refers to scenarios where an externally perceived immutable object (&T) can undergo mutation.

For instances where mutability spans across multiple threads, Mutex, RwLock, or AtomicXXX are the go-to choices, offering similar functionalities:

  • AtomicXXX mirrors Cell, prohibiting interior references and solely allowing movement in and out.
  • RwLock is analogous to RefCell, granting interior references via guards.
  • Mutex can be seen as a streamlined version of RwLock, without differentiating between read-only and write guards. Conceptually, it aligns with a RefCell that only possesses a borrow_mut method.

Bellow we have a simple schematic summarizing all information above.

Rust Wrappers Schema