🐹 Go (Golang) Intermediate

What is sync.Once in Go?

Answer

sync.Once guarantees that a function is executed exactly once, no matter how many goroutines call it concurrently. Its Do(f func()) method runs f only on the first call — subsequent calls do nothing and block until the first invocation completes. This makes it the idiomatic way to implement lazy singleton initialization: var once sync.Once; var instance *DB; func GetDB() *DB { once.Do(func() { instance = connect() }); return instance }. It is safe without any additional locking.