My intention was to create a singleton, but do not know how to handle this in Rust, I have read this and this, but not sure if that's the way to create a simple singleton because one speaks of a "mutable singleton" and the other of a "safe-static-singleton".
Asked
Active
Viewed 1,656 times
3
-
I ask this question because in the previous did not explain well, and already has an answer, so I do this and delete the update of the other, to accept the answer without update – Angel Angel Apr 01 '16 at 19:29
-
Simple answer would be: you don't. It is almost never good idea to use singletons. – Hauleth Apr 01 '16 at 19:34
-
Please describe *what you want to do* with the singleton. If you aren't mutating something, then there are other options. – Shepmaster Apr 01 '16 at 19:35
-
@Shepmaster is not anything in particular, I'm creating things I use in other language, to learn something of Rust. Not mutate, just that it always returns the same instance of the object – Angel Angel Apr 01 '16 at 19:39
-
2I'd warn against blindly copying concepts from other languages as you are less likely to discover the things that make a language unique and useful. Anyway, it sounds like you want a [constant of some kind](http://doc.rust-lang.org/stable/book/const-and-static.html). Follow the instructions to use lazy-static in [this answer](http://stackoverflow.com/a/27826181/155423) and just skip the wrapping `Mutex`. – Shepmaster Apr 01 '16 at 21:52
-
Meta commentary should normally be left in the comments, not the question, and you shouldn't delete your question if it's a duplicate anyway - Stack Overflow uses duplicates to help Googlers find information. – Veedrac Apr 02 '16 at 10:19
1 Answers
6
A singleton is just a lazily initialized piece of static data. That means you really do want lazy-static
.
Note that
For a given
static ref NAME: TYPE = EXPR;
, the macro generates a unique type that implementsDeref<TYPE>
and stores it in a static with nameNAME
.
which means NAME
is actually akin to the constructor of the "singleton", and &*NAME
is the "singleton" itself.

Veedrac
- 58,273
- 15
- 112
- 169