Through sync. Once instance to ensure that the do of a once instance is executed only once, regardless of whether the Func in do has multiple or one, using this feature to implement the singleton pattern in the design pattern, there is no such thing in Golang, so take the structure to test:
Type Singleton struct{}
var ins *singleton
var once sync. Once
Func getins () *singleton {
Once. Do (func () {
INS = &singleton{}
INS = new (singleton)
})
return INS
}
Sync. Once Doc:
Type Once
Once is a object that would perform exactly one action.
Type Once struct {
Contains filtered or unexported fields
}
Func (*once) do
Func (o *once) do (f func ())
Do calls the function f if and only if does is being called for the first time for this instance of Once. In other words, given
var once once
If once. Do (f) are called multiple times, only the first call would invoke F, even if f have a different value in each invocation. A new instance of Once is required for each function to execute.