1) Use lazy_static crate 2) Use a arc wrapped rwlock
1) Use lazy_static crate 2) Use a arc wrapped rwlock
I also get slight PTSD whenever I have to write `new`, not sure if the method will allocate or not behind the scenes. This is one of the things zig gets right I think:
- No hidden control flow.
- No hidden memory allocations.
I agree it's not an easy language to pickup, but the use case you mentioned is a pretty common one and there are several ways to solve it. For example, any kind of config reading from a file needs it. Similarly, connection pools for DB etc are shared this way so its not an uncommon use case in day to day usage of Rust.
In my case, after fighting for literally days, the crate OnceCell did the job (kind of), but I felt awkward retorting to an external crate to deal with a simple static-global-initialize-once-never-touch-again piece of data.
At the very least, you need some sort of locking mechanism to deal with the potential issue where multiple threads try to initialize the variable concurrently. And you need some poisoning mechanism to prevent panics and reentrancy during initialization. Rust makes you realize "oh, yeah, I need to think about these too".
In any case, OnceCell is a very reasonable way to do this and is on track for stabilization.
This application was also single-thread (a command line utility to parse a text file). I now understand that Rust cannot guarantee the safety of initializing global variables so it makes me take the long road, but it could be great it could infer better about each particular case and enforce only when required.
If I can shoot myself in the foot with C then Rust would be kind-of clamping down on me and nailing my feet to the ground. At the end of the day, it hurts more or less the same.
That was my experience as a rookie with Rust in this particular case.
One of the ways Rust is successful at scale is that the intraprocedural analysis is sophisticated, but the interprocedural analysis is deliberately quite basic. It's not quite in keeping with that to do things like selectively enforce bounds on global variables.
For use cases like the one you mentioned, the general strategy Rust wants you to use is to pass around a context with your data inside it (and the data could be in OnceCells if it's lazily fetched). This is also a more testable design. Global state is meant to be used sparingly.