Expand description
Shareable mutable containers.
Rust memory safety is based on this rule: Given an object T
, it is only possible to
have one of the following:
- Having several immutable references (
&T
) to the object (also known as aliasing). - Having one mutable reference (
&mut T
) to the object (also known as mutability).
This is enforced by the Rust compiler. However, there are situations where this rule is not flexible enough. Sometimes it is required to have multiple references to an object and yet mutate it.
Shareable mutable containers exist to permit mutability in a controlled manner, even in the
presence of aliasing. Cell<T>
, RefCell<T>
, and OnceCell<T>
allow doing this in
a single-threaded way—they do not implement Sync
. (If you need to do aliasing and
mutation among multiple threads, Mutex<T>
, RwLock<T>
, OnceLock<T>
or atomic
types are the correct data structures to do so).
Values of the Cell<T>
, RefCell<T>
, and OnceCell<T>
types may be mutated through shared
references (i.e. the common &T
type), whereas most Rust types can only be mutated through
unique (&mut T
) references. We say these cell types provide ‘interior mutability’
(mutable via &T
), in contrast with typical Rust types that exhibit ‘inherited mutability’
(mutable only via &mut T
).
Cell types come in three flavors: Cell<T>
, RefCell<T>
, and OnceCell<T>
. Each provides
a different way of providing safe interior mutability.
§Cell<T>
Cell<T>
implements interior mutability by moving values in and out of the cell. That is, an
&mut T
to the inner value can never be obtained, and the value itself cannot be directly
obtained without replacing it with something else. Both of these rules ensure that there is
never more than one reference pointing to the inner value. This type provides the following
methods: