0 day streak
go / intermediate
Snippet

Guaranteed One-Time Initialization via sync.Once

The sync.Once type guarantees that a function is executed exactly once across all goroutines. This is commonly used for thread-safe lazy initialization, such as setting up global configurations, connection pools, or singletons, without needing explicit locks or manual double-checked locking.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import (
"fmt"
"sync"
)
type Config struct {
Value string
}
var (
instance *Config
once sync.Once
)
func GetConfig() *Config {
once.Do(func() {
instance = &Config{Value: "Initialized"}
})
return instance
}
func main() {
c1 := GetConfig()
c2 := GetConfig()
fmt.Println(c1 == c2) // true
}
Breakdown
1
once sync.Once
Declares a sync.Once variable to coordinate execution state.
2
once.Do(func() { ... })
Executes the passed function exactly once. Subsequent calls to Do block until the first execution completes, and then return immediately without running the function again.
3
return instance
Returns the initialized global pointer, ensuring all callers receive the same reference.