Singleton in go

后端 未结 9 2112
心在旅途
心在旅途 2021-01-30 10:46

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

9条回答
  •  Happy的楠姐
    2021-01-30 11:04

    You should be aware that Once.Do is serious about executing the code only once. That means, the code is always executed only once, even though it might have panicked:

    from https://golang.org/pkg/sync/#Once.Do

    If f (note: the once logic) panics, Do considers it to have returned; future calls of Do return without calling f.

    I used mutexes instead to ensure unique initialisation of a global configuration variable to overcome this restriction:

    • https://golang.org/pkg/sync/#Mutex
    • https://gobyexample.com/mutexes

提交回复
热议问题