Use sync.Once with the Do method to ensure a function runs exactly once across concurrent goroutines.
Use the sync.Once type to ensure a function executes exactly once across multiple goroutines.
var once sync.Once
var result string
func init() {
once.Do(func() {
result = "initialized"
})
}
The Do method takes a function and runs it the first time it 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. It is useful for setting up resources like database connections or loading configuration files so you don't waste time doing it repeatedly. Think of it like a light switch that only works the first time you flip it, ignoring all future attempts.