sync.Once
sync.Once runs a function at most once, even if many goroutines call Do at the same time. Later Do calls wait for the first run to finish, then return without running the function again.
Detailed Explanation
You have an expensive setup: parse a config, connect a default client, compile a regexp. once.Do(setup) from any goroutine guarantees setup runs once. Concurrent callers block until that run completes. If setup panics, Once considers it done; later Do calls do not retry. If you need retry, use a different pattern (a pointer plus mutex, or sync.OnceValues in newer Go for (T, error)).
Do takes a func(). There are no arguments. Close over what you need, or use sync.OnceValue / OnceValues (Go 1.21+) which return the computed value and, for OnceValues, an error.
Not a reset. There is no Once.Reset in the standard library. A new Once is a new guarantee. For tests that need to re-run init, inject a constructor instead of a package-level Once.
Package-level init vs Once. init runs at startup on one goroutine before main. Once runs on first use and can fail as an error if you use OnceValues. Prefer Once (or a constructor) for anything that can fail or that you want to skip in tests.
What it costs. The first Do runs your function. Later Do calls are an atomic load. Do not put changing business logic in Do; put initialization. A Once that starts a goroutine is fine; a Once that you expect to run per request is a bug in the surrounding design.
Code Examples
package main
import (
"fmt"
"sync"
)
var (
once sync.Once
client string
)
func getClient() string {
once.Do(func() {
client = "ready"
})
return client
}
func main() {
fmt.Println(getClient(), getClient())
}func compiled() func(string) bool {
return sync.OnceValue(func() func(string) bool {
re := mustCompile(`^\d+$`)
return re.Match
})()
}
func mustCompile(string) interface{ Match(string) bool } {
return matcher{}
}
type matcher struct{}
func (matcher) Match(string) bool { return true }Common Gotchas
A panic inside `Do` still counts as "done"
later calls do not retry. Recover inside the function if you must retry, or use a mutex and a flag you control.
Do not copy a `Once` after `Do`
the copy has its own "done" bit and may run again, or the original may be half-updated.
`Do(nil)` panics
`Do(nil)` panics