Module 15 Β· Design Patterns in Go β Lesson 4 of 8 Β· ~8 min
Singleton with sync.Once
One shared instance, built exactly once
Singleton guarantees one instance app-wide β one Config, one DB pool, one Stripe client. The honest Go answer first: a package-level variable initialized in var or func init() is already a singleton, created once at startup and shared everywhere. If you can build it eagerly, do that and stop.
You reach for machinery only when construction must be lazy (defer the expensive work until first use) and the program is concurrent β and a Go server always is. Two goroutines hitting Get() at once must not both build the instance.