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.
sync.Once is a tool that guarantees a specific piece of code runs only one time, no matter how many times you ask it to run. It is essential for safely setting up shared resources like database connections or configuration files in a multi-threaded program. Think of it as a one-time switch that flips on the first use and stays on forever, preventing duplicate work.