Skip to content
Tutorials Center
My learning

Topics

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.

Go
var once sync.Once
once.Do(func() { fmt.Println("init") })
once.Do(func() { fmt.Println("never printed") })

Try it

Go Lazy initialization from many goroutines

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.

Go OnceFunc, OnceValue and OnceValues

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

Go
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 if initDB failed. To retry on error, use a mutex and a flag, or let your function report the error through OnceValues and treat the cached error as final.
  • Memory ordering: everything f writes is visible to every goroutine whose Do returns, so you do not need extra locking to read the initialized value afterwards.
  • Do not call Do on the same Once from inside f. That deadlocks, since the inner call waits for the outer one to finish.
  • Never copy a Once after first use; keep it in a package variable or a struct used by pointer.
  • Prefer OnceValue for lazy singletons: var db = sync.OnceValue(openDB) replaces a variable, a Once and a getter function with one line.
  • Zero value is ready to use.
  • One Once per thing initialized. A shared Once guards a single function, not a family of initializations.
  • Package init() functions are better when the work is cheap and always needed; Once shines for expensive or optional setup.