package singleton type singleton struct { O interface{} } var instantiated *single = nil // private instance of singleton func New() *single { if instantiated == nil { instantiated = new(single) } return instantiated }
I think at the very least you need a lock or some other way to avoid a race on the creation of the singleton.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
If I needed to translate a singleton into Go, I would use an empty struct (type singleton struct{}). So the object would not store any state or take up any memory. All “instances” would be interchangeable. Then the state would be in global variables, with initialization protected by a sync.Once.
What do you want it for? Might sound strange but if you control all code you can just not create more than one. Alternatively panic if it can not work with more than one instances.
--
It depends on what you’re trying to do.
The singleton pattern is less useful in Go than in languages like Java where everything is an object. Often you should use package variables and regular functions instead of a singleton object. But sometimes you need to create an object so that you can fulfill an interface. Then it’s useful to create an empty struct that acts like a singleton.
Ian
Hi guys,I am trying to implement a singleton pattern by using Go since I am a Gopher from Java world.There are few questions I currently have.1. in Java, we use synchronized keywords to forbidden multiple threads creating multiple instance then how to do it in Go?2. is singleton pattern a good practice for Go compared to Java?