How to Implement the Singleton Pattern in Go (sync.Once)

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.