O Singleton é um padrão de projeto criacional, que garante que apenas um objeto desse tipo exista e forneça um único ponto de acesso a ele para qualquer outro código.
O Singleton tem quase os mesmos prós e contras que as variáveis globais. Embora sejam super úteis, eles quebram a modularidade do seu código.
Você pode usar classes que dependem de singletons em algumas outras situações. Você terá que levar a classe singleton também. Na maioria das vezes, essa limitação surge durante a criação de testes de unidade.
By definition, Singleton is a global mutable object. In Rust this is a static mut item. Thus, to avoid all sorts of concurrency issues, the function or block that is either reading or writing to a mutable static variable should be marked as an unsafe block.
For this reason, the Singleton pattern can be percieved as unsafe. However, the pattern is still widely used in practice. A good read-world example of Singleton is a log crate that introduces log!, debug! and other logging macros, which you can use throughout your code after setting up a concrete logger instance, such as env_logger. As we can see, env_logger uses log::set_boxed_logger under the hood, which has an unsafe block to set up a global logger object.
In order to provide safe and usable access to a singleton object, introduce an API hiding unsafe blocks under the hood.
See the thread about a mutable Singleton on Stackoverflow for more information.
Starting with Rust 1.63, Mutex::new is const, you can use global static Mutex locks without needing lazy initialization. See the Singleton using Mutex example below.
Safe Singleton
A pure safe way to implement Singleton in Rust is using no global variables at all and passing everything around through function arguments. The oldest living variable is an object created at the start of the main().
local.rs
Output
Lazy Singleton
This is a singleton implementation via lazy_static!, which allows declaring a static variable with lazy initialization at first access. It is actually implemented via unsafe with static mut manipulation, however, it keeps your code clear of unsafe blocks.
lazy.rs
Output
Singleton using Mutex
Starting with Rust 1.63, it can be easier to work with global mutable singletons, although it’s still preferable to avoid global variables in mostcases.
Now that Mutex::new is const, you can use global static Mutex locks without needing lazy initialization.