Cell

Reference Video | Rust doc - cell (module), Cell (struct)

  • Allows mutable sharing
  • No one has a reference to the thing inside a cell. so anyone can modify the cell itself
  • Does not implement Sync
  • can get the value only if:
    1. you have a mutable reference to it (at which point you dont really need a cell)
    2. the type inside implements Copy
  • therefore a cell is usually used for small Copy types
  • useful for when you want multiple things referencing the same thing in a single threaded system
  • Technically all the magic of a Cell is done int the UnsafeCell implementation The compiler has extra info about UnsafeCell and considers it differently. This allows for such behaviour.
  • UnsafeCell implements !Sync and a bunch of other features
  • UnsafeCell also allows us to get an exclusive, mutable reference from a shared reference. This is allowed because the compiler trusts the guy :)