3

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".

6
  • 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 Commented Apr 1, 2016 at 19:29
  • Simple answer would be: you don't. It is almost never good idea to use singletons. Commented Apr 1, 2016 at 19:34
  • Please describe what you want to do with the singleton. If you aren't mutating something, then there are other options. Commented Apr 1, 2016 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 Commented Apr 1, 2016 at 19:39
  • 2
    I'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. Follow the instructions to use lazy-static in this answer and just skip the wrapping Mutex. Commented Apr 1, 2016 at 21:52

1 Answer 1

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 implements Deref<TYPE> and stores it in a static with name NAME.

which means NAME is actually akin to the constructor of the "singleton", and &*NAME is the "singleton" itself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.