4 ms·
I feel your pain as I started to learn Rust recently (again) and found the same problem, coming from C. In my case, after fighting for literally days, the crat
by scoutt 4y ago
I feel your pain as I started to learn Rust recently (again) and found the same problem, coming from C.
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.
- howinteresting 4y agoInitializing global, static state isn't simple at all -- C++ is a prime example for how a bad design for static initializers can go horribly wrong. 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.
- scoutt 4y agoI agree, but I have to say that not all the scenarios are the worst case scenario, and sometimes initialization is just "simple", like it was in my case and in other thousand cases I've worked in my life (I do embedded C mostly single-threaded). 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.
- howinteresting 4y agoYeah, Rust is built from the ground up for programming at scale. One of the consequences is that it makes you think about thread safety from the start. (Imagine if you're on a large team and not everyone is aligned on whether some part of the code is thread-safe or not.) Some things are harder, but the benefit is that you can often make a program multithreaded, and many times faster on real workloads, with just a few minutes of work (an experience that's unmatched in all of programming). 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.