Singleton Pattern in Go
marcio.io
Singleton Pattern in Go
1–10 of 76 posts
Re: Singleton Pattern in Go
#2If you have a bunch of immutable state, then build unexported package variables in the package’s `init` func and export funcs which use those variables.
If you have a bunch of mutable state, then don’t use a singleton.
Re: Singleton Pattern in Go
#3Re: Singleton Pattern in Go
#4Re: Singleton Pattern in Go
#5 func init() {
instance = &singleton{}
}Re: Singleton Pattern in Go
#6Re: Singleton Pattern in Go
#7Re: Singleton Pattern in Go
#8This seems more idiomatic: func init() { instance = &singleton{} }
var instance = &singleton{}
In fact, a lot of idiomatic Go will ignore the Get() method, exporting the instance itself:
var Instance = &singleton{}
Clearly if you overwrite it, bad things will happen. Don't do that.
There may possibly be a problem with unnecessarily slowing startup times in the case you don't need the singleton and initialization is more complicated than a malloc - in which case, profiling will tell you and you can revert to the method in the blog post.
Remember that Go's strict import/dependency requirements mean you're unlikely to import the package (and trigger the initialization) unless you actually use the singleton.
It is non-idiomatic to use the sync.atomic package.