Error code E0492
A borrow of a constant containing interior mutability was attempted.
Erroneous code example:
ⓘ
A const
represents a constant value that should never change. If one takes
a &
reference to the constant, then one is taking a pointer to some memory
location containing the value. Normally this is perfectly fine: most values
can't be changed via a shared &
pointer, but interior mutability would allow
it. That is, a constant value could be mutated. On the other hand, a static
is
explicitly a single memory location, which can be mutated at will.
So, in order to solve this error, use statics which are Sync
:
You can also have this error while using a cell type:
ⓘ
This is because cell types do operations that are not thread-safe. Due to this, they don't implement Sync and thus can't be placed in statics.
However, if you still wish to use these types, you can achieve this by an unsafe wrapper:
Remember this solution is unsafe! You will have to ensure that accesses to the cell are synchronized.