Any trick to initialize an RC for a static mut?


#1

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: https://stackoverflow.com/questions/27791532/how-do-i-create-a-global-mutable-singleton. 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?)

Thanks!


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

https://crates.io/crates/lazy_static

Enjoy!


#3

I don’t want something that requires Sync.

Question is still open.


#4

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.

https://play.rust-lang.org/?gist=5b95250582535ac98cf8b73714d85b2d&version=stable


#5

Yeah I know the implications of non-Sync.

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


#6

How about this one: https://play.rust-lang.org/?gist=f448fd3d18ef6281a84ec701a92e1e84&version=nightly