4 ms·
I assume the parent meant that there was no compiler magic at play, as far as I know UnsafeCell is written in pure Rust, just using unsafe code: https://doc.rus
by simias 7y ago
I assume the parent meant that there was no compiler magic at play, as far as I know UnsafeCell is written in pure Rust, just using unsafe code: https://doc.rust-lang.org/src/core/cell.rs.html#1486-1488 https://doc.rust-lang.org/src/core/cell.rs.html#1486-1488
So basically if Rust's stdlib didn't provide it, you could reimplement it yourself from scratch.
EDIT: actually, reading the comments, it looks like I'm wrong about that:
> If you have a reference `&SomeStruct`, then normally in Rust all fields of `SomeStruct` are immutable. The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or mutated, and that `&mut T` is unique. `UnsafeCell<T>` is the only core language feature to work around the restriction that `&T` may not be mutated.
- jrvidal 7y agoI'm not sure that's correct. `UnsafeCell` is a Rust lang item that might disable some optimizations, I think? https://doc.rust-lang.org/src/core/cell.rs.html#1483 https://doc.rust-lang.org/src/core/cell.rs.html#1483
- simias 7y agoYou're right, I just saw that. Well I least I learned something new about Rust today!
- aratakareigen 7y agoYep, you can't implement UnsafeCell yourself without running into undefined behavior.
- Sean1708 7y agoWRT your edit: #[lang = "unsafe_cell"] This tells you that UnsafeCell is a Language Item[1], which basically means that the compiler does have knowledge of it. [1]: https://doc.rust-lang.org/beta/unstable-book/language-features/lang-items.html https://doc.rust-lang.org/beta/unstable-book/language-featur...
- estebank 7y agoThis annotation let's the compiler treat their items in special ways, but it is usually for either easier way to refer to them (I want to desugar this type to a cell of what I already have) or for diagnostics. I think box is one of the few "magical" things in the language.