春のセール
Singleton

Singleton を Rust で

Singleton 生成に関するデザインパターンの一つで この種類のオブジェクトがただ一つだけ存在することを保証し 他のコードに対して唯一のアクセス・ポイントを提供します

Singleton には 大域変数とほぼ同じ長所と短所があります 両方とも随分と便利ですが コードのモジュール性を犠牲にしています

シングルトンのクラスに依存しているあるクラスを使う場合 シングルトンのクラスも一緒に使う必要があります ほとんどの場合 この制限は ユニット・テストの作成で問題となります

Rust specifics

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.

他言語での Singleton

Singleton を C# で Singleton を C++ で Singleton を Go で Singleton を Java で Singleton を PHP で Singleton を Python で Singleton を Ruby で Singleton を Swift で Singleton を TypeScript で