views:

319

answers:

5
+3  Q: 

Singleton in go

How does one implement the Singleton design pattern in the go programming language?

+8  A: 

Before trying to find a way to bend Go to your will, you might want to take a look at some articles:

In summary, over time people have found singletons to be less than optimal, and imho especially if you are trying to do any test-driven development: on many levels they are pretty much as bad as global variables.

[disclaimer: I know its not a strict answer to your question but it really is relevant]

jkp
+1  A: 

Just put your variables and functions at the package level.

Also see similar question: How to make a singleton in Python

hasen j
+1  A: 

Just have a single static, final, constant, global, application-wide instance of the Object you want.

This however contradicts the OO paradigm. Its use should be limited to primitives and immutable objects, not to mutable objects.

BalusC
It only contradicts what Java schools teach about OO
hasen j
+2  A: 

You can do initialization using the once package:

This will ensure that your init methods only get called once.

marketer
+2  A: 

Setting aside the argument of whether or not implementing the singleton pattern is a good idea, here's a possible implementation:

package singleton

type single struct {
        O interface{};
}

var instantiated *single = nil

func New() *single {
        if instantiated = nil {
                instantiated = new(single);
        }
        return instantiated;
}

single and instantiated are private, but New() is public. Thus, you can't directly instantiate single without going through New(), and it tracks the number of instantiations with the private boolean instantiated. Adjust the definition of single to taste.

See also, hasan j's suggestion of just thinking of a package as a singleton.

esm
Having not tested this code, it looks to me like you'd only be able to get an instance of single the first time you call New(). After that, you just get nil. If you lose track of your one instance and it gets garbage collected, you can't create any more. Wouldn't you want to keep track of the pointer to the instance of single and return that instead of nil?
Evan Shaw
Agreed; I've changed the code to do so, although linguistically I'm not very happy with New() returning something other than a fresh object. In another language, I probably would have raised an exception when trying to instantiate the object a second time. Note that, with this approach, the singleton will never actually go out of scope.
esm
Also, I'll point out again that a better way to think about this is probably hasen j's Pythonic approach: treat a package as your singleton, which the language enforces for you already.
esm