Globals /singletons


whats the best way to do these… I have some code thats unfortunately messy due to slotting into frameworks that break my prefered ‘pass everything from above’ setup, by requiring you to submit argument-less functions for it to work with (yuck),

I’ve ended up making static mut g_foo:Option=None, where I cache the values; those are accessed through unsafe blocks…

… is there a safe abstraction in the stdlib for this sort of thing?


There is always that you can use but in general I would recommend to try to not use globals / singletons.


I would recommend to try to not use globals / singletons.

sure, I hate them :slight_smile:
unfortunately I sometimes find myself interfacing with things that simply don’t let you work any other way (‘pass a main loop function which has no args to some C based frame work that will call it’)

the anti-globals mentality is ceratinly one of the things I like most about rust


C APIs that doesn’t let you specify a user data pointer is really annoying :frowning:


right. It’s not the fact that it’s C that is at fault … it’s C used in an especially annoying way.

I’ve worked with people in real life who resist the ‘no globals’ idea, but that might be less common in our present concurrent/parallel world.


Yeah. I want to clarify also my statement was meant for C based callback APIs. For callbacks one should always allow a user pointer otherwise the user of the API will have to resort to using global vars (if state is needed which is very common)