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. Both Cell<T> and RefCell<T> allows to do this in a single threaded
way. However, neither Cell<T> nor RefCell<T> are thread safe (they do not implement
Sync). If you need to do aliasing and mutation between multiple threads it is possible to
use Mutex,
RwLock or
atomic types.

Values of the Cell<T> and RefCell<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 that Cell<T> and RefCell<T> provide 'interior mutability', in contrast
with typical Rust types that exhibit 'inherited mutability'.

Cell types come in two flavors: Cell<T> and RefCell<T>. Cell<T> implements interior
mutability by moving values in and out of the Cell<T>. To use references instead of values,
one must use the RefCell<T> type, acquiring a write lock before mutating. Cell<T> provides
methods to retrieve and change the current interior value:

For types that implement Copy, the get method retrieves the current interior value.

For types that implement Default, the take method replaces the current interior value
with Default::default() and returns the replaced value.

For all types, the replace method replaces the current interior value and returns the
replaced value and the into_inner method consumes the Cell<T> and returns the interior
value. Additionally, the set method replaces the interior value, dropping the replaced
value.

RefCell<T> uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
claim temporary, exclusive, mutable access to the inner value. Borrows for RefCell<T>s are
tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
statically, at compile time. Because RefCell<T> borrows are dynamic it is possible to attempt
to borrow a value that is already mutably borrowed; when this happens it results in thread
panic.

The more common inherited mutability, where one must have unique access to mutate a value, is
one of the key language elements that enables Rust to reason strongly about pointer aliasing,
statically preventing crash bugs. Because of that, inherited mutability is preferred, and
interior mutability is something of a last resort. Since cell types enable mutation where it
would otherwise be disallowed though, there are occasions when interior mutability might be
appropriate, or even must be used, e.g.

Many shared smart pointer types, including Rc<T> and Arc<T>, provide containers that can be
cloned and shared between multiple parties. Because the contained values may be
multiply-aliased, they can only be borrowed with &, not &mut. Without cells it would be
impossible to mutate data inside of these smart pointers at all.

It's very common then to put a RefCell<T> inside shared pointer types to reintroduce
mutability:

Occasionally it may be desirable not to expose in an API that there is mutation happening
"under the hood". This may be because logically the operation is immutable, but e.g. caching
forces the implementation to perform mutation; or because you must employ mutation to implement
a trait method that was originally defined to take &self.

usestd::cell::RefCell;
structGraph {
edges: Vec<(i32, i32)>,
span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
}
implGraph {
fnminimum_spanning_tree(&self) ->Vec<(i32, i32)> {
// Create a new scope to contain the lifetime of the// dynamic borrow
{
// Take a reference to the inside of cache cellletmutcache=self.span_tree_cache.borrow_mut();
ifcache.is_some() {
returncache.as_ref().unwrap().clone();
}
letspan_tree=self.calc_span_tree();
*cache=Some(span_tree);
}
// Recursive call to return the just-cached value.// Note that if we had not let the previous borrow// of the cache fall out of scope then the subsequent// recursive borrow would cause a dynamic thread panic.// This is the major hazard of using `RefCell`.self.minimum_spanning_tree()
}
}Run

This is simply a special - but common - case of the previous: hiding mutability for operations
that appear to be immutable. The clone method is expected to not change the source value, and
is declared to take &self, not &mut self. Therefore any mutation that happens in the
clone method must use cell types. For example, Rc<T> maintains its reference counts within a
Cell<T>.