Go Reference ยท Concurrency and Context
Go sync.Once, OnceFunc and OnceValue
Reference for Go sync.Once, OnceFunc, OnceValue and OnceValues: lazy initialization, singletons, panic behavior and caching a computed result safely.
sync.Once guarantees that a function runs exactly once, no matter how many goroutines ask for it at the same time. The first caller of Do(f) runs f; all other callers wait until it has finished and then return without running it. This is the standard way to initialize shared state lazily and safely.
Go 1.21 added three helpers that wrap a function so it runs once: OnceFunc for functions with no result, OnceValue for one result, and OnceValues for two (usually a value and an error). They remember the result, so later calls return it immediately.
var once sync.Once once.Do(func() { fmt.Println("init") }) once.Do(func() { fmt.Println("never printed") })
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Once struct{ /* ... */ } func (o *Once) Do(f func()) func OnceFunc(f func()) func() func OnceValue[T any](f func() T) func() T func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)
| Name | Description |
|---|---|
f |
The function to run once. Do takes a function with no parameters and no results; wrap other calls in a closure. |
Returns: Do returns nothing. The Once... helpers return a function that runs f on its first call and then returns the saved results.
Panics: if f panics, Once.Do considers f finished, so later calls do nothing and the panic is not repeated. The helpers differ: they panic again with the same value on every call.
Usage notes
- A failed first attempt is not retried.
once.Do(initDB)will never run again even ifinitDBfailed. To retry on error, use a mutex and a flag, or let your function report the error throughOnceValuesand treat the cached error as final. - Memory ordering: everything
fwrites is visible to every goroutine whoseDoreturns, so you do not need extra locking to read the initialized value afterwards. - Do not call
Doon the sameOncefrom insidef. That deadlocks, since the inner call waits for the outer one to finish. - Never copy a
Onceafter first use; keep it in a package variable or a struct used by pointer. - Prefer
OnceValuefor lazy singletons:var db = sync.OnceValue(openDB)replaces a variable, aOnceand a getter function with one line. - Zero value is ready to use.
- One
Onceper thing initialized. A sharedOnceguards a single function, not a family of initializations. - Package
init()functions are better when the work is cheap and always needed;Onceshines for expensive or optional setup.