From the std::cell documentation, I see that Cell
is \"only compatible with types that implement Copy
\". This means I must use RefCell
TL; DR: Cell
when you can.
Long answer: Cell
and RefCell
have a similar name because they both permit the interior mutability, but they have a different purpose:
Cell
It is a wrapper around T
that forbids to share it multiple times at once: you cannot borrow immutably the inner data. This wrapper does not have any overhead, but because of this limitation, you can only do the following operations:
T
is Copy
able, thus).Thanks to its limitation, the Cell
behaves like an exclusive borrow, aka a &mut T
. Therefore, it is always safe to change the inner value. To summarize:
RefCell
It is a wrapper around T
that "removes" the compile-time borrow-checks: the operations that modify the inner value take a shared reference &self
to the RefCell
. Normally, this would be unsafe, but each modifying operation firstly verify that the value was not previously borrowed. The exclusivity of a mutable borrow is verified at runtime.
To summarize:
The advantages and limitations are a mirror of each other. The answer to your question is: if the limitations of Cell
do not bother you, use it, because beside this, it has only advantages. However, if you want a more flexible interior mutability, use RefCell
.