How to Use sync.Once in Go for One-Time Initialization

Use sync.Once with the Do method to safely execute initialization code exactly once in concurrent Go programs.

Use sync.Once to ensure a function runs exactly once, even when called concurrently by multiple goroutines.

var once sync.Once
var config *Config

func initConfig() {
    once.Do(func() {
        config = loadConfig()
    })
}

The Do method accepts a function that executes only the first time Do is called; subsequent calls return immediately without re-executing the function.