How do I use sync.Once for initialization in Go?

Using sync.Once for Initialization in Go

In Go, the sync.Once type is used to ensure that a particular piece of code is only executed once, making it perfect for initializing resources like configuration settings, database connections, or any other startup tasks. It's especially useful in concurrent programming scenarios where multiple goroutines might attempt to execute initialization code simultaneously.

Example of Using sync.Once

package main import ( "fmt" "sync" ) var once sync.Once var instance *Config type Config struct { // Add your config fields here DBName string } func GetConfig() *Config { once.Do(func() { instance = &Config{ DBName: "my_database", } }) return instance } func main() { config := GetConfig() fmt.Println(config.DBName) }

Go sync.Once concurrency initialization goroutines