Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can create a simple basic singleton?

Tags:

rust

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

like image 861
Angel Angel Avatar asked Feb 16 '26 22:02

Angel Angel


1 Answers

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.

like image 80
Veedrac Avatar answered Feb 19 '26 15:02

Veedrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!