Implement the Singleton pattern in Go using sync.Once to ensure thread-safe, one-time initialization of a global instance.
Use sync.Once to ensure a function runs exactly once, even across multiple goroutines.
var instance *MyType
var once sync.Once
func GetInstance() *MyType {
once.Do(func() {
instance = &MyType{}
})
return instance
}
The once.Do call guarantees the initialization logic executes only the first time GetInstance is called, returning the same instance thereafter.
The Singleton pattern ensures only one copy of an object exists in your program. In Go, sync.Once acts like a one-time switch that runs a setup task exactly once, no matter how many people try to flip it at the same time. This prevents errors where multiple threads try to create the same resource simultaneously.