When I can use either Cell or RefCell, which should I choose?

前端 未结 3 1997
傲寒
傲寒 2020-12-01 17:40

From the std::cell documentation, I see that Cell is \"only compatible with types that implement Copy\". This means I must use RefCell

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 18:11

    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:

    • Set the inner value,
    • Swap the inner value with something else,
    • Copy the inner value (only when T is Copyable, 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:

    • Advantage: no overhead
    • Advantage: always mutable
    • Limitation: some operations are impossible

     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:

    • Limitation: a very small overhead
    • Limitation: not always mutable, if it was previously mutably borrowed (beware, some operations may panic in this case)
    • Advantage: you are not limited with the operations that you can do

    What should you chose?

    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.

提交回复
热议问题