|
|
|
|
|
by option_greek
2000 days ago
|
|
Sorry for got to mention the 'mutable' part. So a mutable singleton variable that has to be marked with an unsafe keyword (and forces the functions that use to be marked as unsafe). The other day I was struggling to implement a singleton (for loading large data from disk) and finally decided to just pass it down the whole chain from the main method. May be I'm missing some easy pz way of doing this ? |
|
First of all, I find that many people aren't using multiple threads, and therefore, what they want is a thread-local, not a static. For that, you can use https://doc.rust-lang.org/stable/std/macro.thread_local.html
If you do need a static, then there are libraries like https://docs.rs/lazy_static/1.4.0/lazy_static/ and https://crates.io/crates/once_cell to help too. We have talked about adding something like this to the standard library, but it hasn't landed yet. https://github.com/rust-lang/rust/issues/74465 is the tracking issue for when it does. The reason that we don't have this yet is that it is not super urgent, given that the libraries already exist.
Now, both of those give you immutable statics, but that's where interior mutability comes in. As you can see from the thread_local examples, you can use a RefCell there, and if your type is simple enough, maybe even regular Cell. For lazy_static or once_cell, you may want to use Mutex<T>, or RwLock<T>, or some other type. For simple integers, the various Atomic* types might be better, for example. The reason this isn't built in is exactly because there are so many options; people need all of these specifics, so we have to provide them, so there's no single built-in thing.