|
|
|
|
|
by Jabbles
3991 days ago
|
|
If instance can truly be initialized like that, then there's no need for the init() function, just do it at the top level: 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. |
|
Not just in that case. If you lazily initialize then you can get other things done before—or while—you're waiting for the singleton constructor to run. Global constructors are suboptimal for performance almost as a rule.