I was reading the rust std doc and came across this line:
UnsafeCell<T> opts-out of the immutability guarantee for &T: a shared reference &UnsafeCell<T> may point to data that is being mutated. This is called “interior mutability”.
Does this mean one can create thier own version of UnsafeCell<T> and opt out of alias based optimizations done on &T ? How does UnsafeCell<T> inform rustc that it should not do alias based optimizations ? Is there some attribute for it or is the rustc compiler written to recognize UnsafeCell<T> with a hard coded built in rule ?
>Solution :
You can read all of this up on your own, the source code is free to browse after all. UnsafeCell behaves how it does because it’s declared as implementing the language item unsafe_cell:
#[lang = "unsafe_cell"] #[stable(feature = "rust1", since = "1.0.0")] #[repr(transparent)] pub struct UnsafeCell<T: ?Sized> { value: T, }
If you don’t include core you can implement your own version, but only on nightly since it requires 2 features to be enabled:
#![feature(no_core, lang_items)]
#![no_core]
#[lang = "unsafe_cell"]
#[repr(transparent)]
struct MyUnsafeCell<T: ?Sized> {
v: T
}