What is the purpose of sync.Once, and how does it guarantee a piece of code runs exactly once?

Last updated 20 June 2026

  • sync.Once ensures a function runs exactly once across all goroutines via Do(f). It is the idiomatic tool for thread-safe lazy initialization (singletons, config).

  • It uses an atomic done flag as a fast path and a mutex as the slow path. Concurrent callers block until the first finishes, so all see completed initialization.

  • If f panics, the Once still counts as done and never retries. Never copy a Once after first use.

  • https://www.guru99.com/golang-interview-questions.html
All Golang interview questions