💾 Archived View for carnage.edvinbasil.com › knowledge › pl › rust › cell.md captured on 2021-12-17 at 13:26:06. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2020-11-07)

-=-=-=-=-=-=-

Cell

[Reference Video](https://youtu.be/8O0Nt9qY_vo?t=466) | Rust doc - [cell (module)](https://doc.rust-lang.org/std/cell/index.html), [Cell (struct)](https://doc.rust-lang.org/std/cell/struct.Cell.html)

- 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 :)