Re:Rust – How do I create a global, mutable singleton? (2015)
by heinrich5991 on Wednesday July 22, 2020 @04:00PM
(#23920945)
You can do that in Rust by creating your own abstraction around `UnsafeCell`. Say `InitializeCell`:
[ Parent
| on HN ]
Re:Rust – How do I create a global, mutable singleton? (2015)
by richard_todd on Wednesday July 22, 2020 @05:20PM
(#23921727)
That's actually really nice. It does appear that Rust will peel all the layers away when opt-level is 2 or higher. I could live with that. You can (re)set the value from anywhere, but at least it has to be marked unsafe. Fair enough!
When I tried to do this a couple years ago (with mem::uninitialized), I failed to get something usable. I think I was also concerned that having to use unsafe for the reads would prohibit compiler optimizations, even if it could be wrapped in a safe wrapper as you did here. Maybe that was worrying for nothing. Maybe it's time to try Rust again.