Any trick to initialize an RC for a static mut?


I’m trying to provide an reasonable way for callback functions to get access to a handle without passing the handle around (let’s just stipulate that for the next few moments that this is reasonable).

I’d like to do something like:

fn get_handle() -> Rc<RefCell<usize>> {
        static mut x :Rc<RefCell<usize>> = Rc::new(RefCell::new(0));
        unsafe { x.clone() }

but of course I can’t call Rc::new() for a static mut.

Is there some reasonable trick for getting around this?

The obvious thing is to do pointers & other chicanery (which seems to be what rust internals do in such situations), but I’m wondering if there’s a more reasonable approach in nightly.

For an example, see: Adapting that code to just a usize you’d get something like:

fn get_internal_wr() -> Rc<RefCell<usize>> {
        static mut singleton : *const Rc<RefCell<usize>> =
                                        0 as * const Rc<RefCell<usize>>;
        static once : Once = ONCE_INIT;
        unsafe {
                once.call_once(|| {
                        // Make it
                        let x = Rc::new(RefCell::new(0));
                        // Put it in the heap so it can outlive this call
                        singleton = mem::transmute(Box::new(x));
        unsafe { (*singleton).clone() }

Which appears “to work”, but is kind of nuts.

(Related, is it better to do: “singleton = Box::into_raw(Box::new(x));” instead of the transmute?)


How to rework code w/ "can't use type parameter from outer fn..."



I don’t want something that requires Sync.

Question is still open.


If you want it to be not Sync, then you can put it into Thread Local Storage.

A non Sync would be unsafe to access from multiple threads.


Yeah I know the implications of non-Sync.

Thread local improves the definition, but it makes all the uses even worse than RefCell unfortunately.


How about this one: